• JAVA 图片png和jpeg格式的转化方式


    最近遇到一些需求,需要对图片做格式转化,比如将png图片转为jpeg,或者将jpeg转为png,网上有部分代码,但是发现有些是不正确的,

    毕竟png是4通道,32位,而jpeg是3通道,24位,因此两个图片之间转化时,肯定需要注意这些问题,而不是简单的图片内容的转化。

    下面小编是小编亲测实用的java方法:

    public class ImageConvert {
    
        private static final String IMAGE_PATH_PNG = "F:\Gis开发\学习资料\tile\3_0_1.png";
        private static final String IMAGE_PATH_PNG_NEW = "F:\Gis开发\学习资料\tile\3_0_1_new.png";
        private static final String IMAGE_PATH_JPEG = "F:\Gis开发\学习资料\tile\3_0_1.jpg";
        private static final String IMAGE_PATH_JPEG_NEW = "F:\Gis开发\学习资料\tile\3_0_1_new.jpg";
    
        public static void main(String[] args) {
            png2jpeg();
        }
    
        public static void png2jpeg() {
            //读取图片
            FileOutputStream fos =null;
            try {
                BufferedImage bufferedImage = ImageIO.read(new File(IMAGE_PATH_PNG));
                //转成jpeg、
                BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(),
                                                                 bufferedImage.getHeight(),
                                                                 BufferedImage.TYPE_INT_RGB);
                bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null);
                fos = new FileOutputStream(IMAGE_PATH_JPEG_NEW);
                ImageIO.write(bufferedImage,"jpg",fos);
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    fos.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    
        public static void jpeg2png() {
            //读取图片
            try {
                BufferedImage bufferedImage = ImageIO.read(new File(IMAGE_PATH_JPEG));
                //转成png、
                BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(),
                                                                bufferedImage.getHeight(),
                                                                BufferedImage.TYPE_INT_ARGB);
                bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null);
                FileOutputStream fos = new FileOutputStream(IMAGE_PATH_PNG_NEW);
                ImageIO.write(bufferedImage1,"png",fos);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    SharePoint Forums使用
    使用JS隐藏MOSS菜单
    缓存
    异步委托
    一个层动态放大的例子的一些知识点
    petshop之购物车再思考
    设置防止攻击session(疑惑)
    petshop异步和多线程
    Profile在petshop
    一个简单的显示隐藏知识点
  • 原文地址:https://www.cnblogs.com/ljy-20180122/p/13283564.html
Copyright © 2020-2023  润新知