Java PNG to JPG Bug

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

I am trying to convert a PNG image to a JPEG image following this tutorial. But I encounter a problem. The resulting image has a pink layer.

Does anyone have a solution for this problem? Or what code should I use in order to convert the image into the desired format?

Thanks in advance!

回答1:

  1. Create a BufferedImage of desired size, e.g.:

    BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB)

  2. fill it with a proper background color:

    img.getGraphics().fillRect(....)

  3. Call drawImage on the image's graphics atop of that background:

    img.getGraphics().drawImage(image, 0, 0, null);

then write down your image as JPG as usual.



回答2:

Which color mode are you using? While you create buffered image object, try adding the type like this option.

    File newFile = new File(path + fileName + "." + Strings.FILE_TYPE);      Image image = null;     try {         image = ImageIO.read(url); // I was using an image from web     } catch (IOException e1) {         e1.printStackTrace();     }      image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);     try {         BufferedImage img = toBufferedImage(image);         ImageIO.write(img, "jpg", newFile);     } catch (IOException e) {         e.printStackTrace();     }    }  private static BufferedImage toBufferedImage(Image src) {     int w = src.getWidth(null);     int h = src.getHeight(null);     int type = BufferedImage.TYPE_INT_RGB; // other options     BufferedImage dest = new BufferedImage(w, h, type);     Graphics2D g2 = dest.createGraphics();     g2.drawImage(src, 0, 0, null);     g2.dispose();     return dest; } 


文章来源: Java PNG to JPG Bug
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!