美文网首页
java 保存图片

java 保存图片

作者: Lost_Robot | 来源:发表于2018-12-20 13:31 被阅读4次

使用BufferedImage生成图片
保存图片有两种方式:
1.JPEGImageEncoder
该种方式保存的图片会失真,而且图片还大,不建议使用;


            BufferedImage image;
        BufferedOutputStream bos = null;
        if (image != null) {
            try {
                FileOutputStream fos = new FileOutputStream("E:\\testPic.png");
                bos = new BufferedOutputStream(fos);

//              image.getGraphics().drawImage(
//                      image.getScaledInstance(imageWidth, imageHeight,java.awt.Image.SCALE_SMOOTH), 0, 0, null);

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
                encoder.encode(image);
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {// 关闭输出流
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

JPEGImageEncoder 图片效果

2.使用ImageIO保存图片
推荐使用,图片精度高,size小;


    // 得到图形对象
        Graphics2D g2d = image.createGraphics();
        // 将窗口内容面板输出到图形对象中
    //  content.printAll(g2d);
        // 保存为图片
        File f = new File("E:\\testPic.png");
        try {
            ImageIO.write(image, "png", f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 释放图形对象
        g2d.dispose();
ImageIO 图片效果

相关文章

网友评论

      本文标题:java 保存图片

      本文链接:https://www.haomeiwen.com/subject/uwxykqtx.html