首页 > 其他分享 >12.13每日总结

12.13每日总结

时间:2023-12-13 22:15:14浏览次数:24  
标签:总结 java String 每日 IOException 12.13 import new image

package tuxiang;

import okhttp3.*;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.net.URLEncoder;

public class ImageConverter extends JFrame implements ActionListener {
    private JTextField imageField;
    private JLabel originImageLabel;
    private JLabel resultImageLabel;

    public static final String API_KEY = "ldQefiX4omFzf2e3dDEESqGG";
    public static final String SECRET_KEY = "0slIQkoLw1QYk4AvAbMe3NFA03u2P6It";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public ImageConverter() {
        // 设置窗口标题
        setTitle("Image Converter");
        // 设置窗口大小
        setSize(1200, 700);
        // 设置窗口关闭时退出程序
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建主面板
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 创建选择文件按钮和文本框
        JButton selectButton = new JButton("选择图片");
        selectButton.addActionListener(this);
        imageField = new JTextField();
        imageField.setEditable(false);

        // 显示原始图片的标签
        originImageLabel = new JLabel();

        // 创建转换按钮
        JButton convertButton = new JButton("图片特效");
        convertButton.addActionListener(this);

        // 创建结果图片标签
        resultImageLabel = new JLabel();

        // 添加组件到主面板
        panel.add(selectButton, BorderLayout.NORTH);
        panel.add(imageField, BorderLayout.CENTER);
        panel.add(originImageLabel, BorderLayout.WEST);
        panel.add(convertButton, BorderLayout.SOUTH);
        panel.add(resultImageLabel, BorderLayout.EAST);

        // 将主面板添加到窗口
        add(panel);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("选择图片")) {
            JFileChooser fileChooser = new JFileChooser();
            int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                String imagePath = fileChooser.getSelectedFile().getAbsolutePath();
                imageField.setText(imagePath);
                showOriginImage(imagePath);
            }
        } else if (e.getActionCommand().equals("图片特效")) {
            String imagePath = imageField.getText();
            try {
                String base64Image = getFileContentAsBase64(imagePath, true);
                String convertedImage = convertImage(base64Image);
                showResultImage(convertedImage);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void showOriginImage(String imagePath) {
        try {
            BufferedImage image = ImageIO.read(new File(imagePath));
            if (image != null) {
                ImageIcon icon = new ImageIcon(image.getScaledInstance(450, 450, Image.SCALE_SMOOTH));
                originImageLabel.setIcon(icon);
            } else {
                System.err.println("Error: Failed to load image");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error loading image: " + e.getMessage());
        }
    }
    private String convertImage(String base64Image) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "type=anime&image=" + base64Image);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();
        JSONObject jsonResponse = new JSONObject(responseBody);
        return jsonResponse.getString("image");
    }

    private void showResultImage(String base64Image) {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        try {
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
            ImageIcon icon = new ImageIcon(image.getScaledInstance(450, 450, Image.SCALE_SMOOTH));
            resultImageLabel.setIcon(icon);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    private static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ImageConverter gui = new ImageConverter();
            gui.setVisible(true);
        });
    }
}

  

标签:总结,java,String,每日,IOException,12.13,import,new,image
From: https://www.cnblogs.com/louwangshayu/p/17900046.html

相关文章

  • Linux课堂知识总结7
     在这节课的学习中,我们学习了Linux的存储管理操作。1.初识硬盘机械HDD固态SSD固态的优势:SSD采用电子存储介质进行数据存储和读取的一种技术,突破了传统机械硬盘的性能瓶颈,拥有极高的存储性能,被认为是存储技术发展的未来新星。2.分区类型 主分区:正常情况使用的分区......
  • 12.13 闲话
    昨天\(12.12\)今年是西安事变\(87\)周年所以\(\mathrm{CCF}\)送给\(\mathrm{HE}\)省队一个\(\mathrm{HE}\)事变,现在看起来大家都已经快似了(悲)今天打了个Hash水题???企鹅DescriptionPenguinQQ是中国最大、最具影响力的SNS(SocialNetworkingServices)网站,以实名制为基础,为用户......
  • 闲话12.13
    摆。上午ds,vjudge题单刚开就切了七道,妈的树点涂色啥时候加的hack,吃了两发罚时下午才改掉这题。上午喜提rk2。刚开始讲20min就开始肚子难受,窜了。感觉宿舍又热又冷的,还没睡觉的时候热的要死,睡着了又能着凉,难受。最近两天还上火了,不爽。但是ds有一半都听懂了,赢。于是后......
  • 每日总结12.13
    今天完成软件构造的大作业中,一直报这个错误,目前不知道是什么原因,还没解决。在解决的过程中发现可能和下面有关,但都没有问题,之后再换个办法解决吧。确认Maven或Gradle依赖配置是否正确:如果你使用Maven或Gradle进行依赖管理,确保在你的配置文件中添加了OkHttp依赖。你......
  • 每日总结
    面向对象设计原则1、开闭原则开闭原则的定义:软件实体应当对扩展开放,对修改关闭。如何实现开闭原则:抽象化是开闭原则的关键,提供相对稳定的抽象层和灵活的具体层。2、里氏替换原则所有引用基类的地方必须能透明地使用其子类的对象里氏代替原则的实现方法:子类可以扩展父类的功......
  • 12.13日记
    今天开始复习软件设计,先是UML的基础知识  在UML中存在两种建模机制:静态建模机制和动态建模机制。   当我们在实际的应用中使用面向对象的设计和分析方法时,一般遵循的步骤是:第一步,描述需求;   这个步骤一般产生用例图。第二步,根据需求建立系统的静态模型,构造系统的结......
  • 知识库搭建工具年度总结来啦!赶紧收藏!
    随着信息时代的到来,知识管理变得越来越重要。无论是个人还是企业,都需要一个高效的知识库来存储和管理各种知识资源。为了帮助大家搭建一个优秀的知识库,我将为大家推荐4款知识库搭建工具。下面我们一起来了解这些工具吧!HelpLookHelpLook是一款功能强大的知识库搭建工具。它提供了全......
  • 12/13每日总结
    拓扑排序简介拓扑排序就是找到做事的先后顺序每个AOV网可能有一个或者多个拓扑排序实现①从AOV网中选择一个没有前驱(入度为0)的顶点并输出。②从网中删除该顶点和所有以它为起点的有向边。③重复①和②直到当前的AOV网为空或当前网中不存在无前驱的顶点为止。使用三个数组进行实现......
  • 12/13每日总结
    拓扑排序简介拓扑排序就是找到做事的先后顺序每个AOV网可能有一个或者多个拓扑排序实现①从AOV网中选择一个没有前驱(入度为0)的顶点并输出。②从网中删除该顶点和所有以它为起点的有向边。③重复①和②直到当前的AOV网为空或当前网中不存在无前驱的顶点为止。使用三个数组进行实现......
  • 网络流小总结
    \[\Huge\color{lightblue}\text{网络流启动}\]概念网络边带权的有向图,只存在一个原点\(s\)和汇点\(t\)。边\(<u,v>\)的权值\(c(u,v)\)表示这个点的容量。流\(f(u,v)\)满足:流量限制,即\(f(u,v)\leqc(u,v)\)。流量守恒,即对\(u\nes,u\net\),\(\sumf(u,v)=\sumf......