Gwalk Gwalk - 2 months ago 26
Java Question

Java ARGB to JPG

How can I save BufferedImage with TYPE_INT_ARGB to jpg?

Program generates me that image:

enter image description here

And it's OK, but when I save it in that way:

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(byteStream);
try {
ImageIO.write(buffImg, "jpg", bos);
// argb
byteStream.flush();
byte[] newImage = byteStream.toByteArray();

OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\test.jpg"));
out.write(newImage);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


The result is:
enter image description here

Understand that this is due to the alpha layer, but don't know how to fix it. Png format does not suit me, need jpg.

Answer

OK! I've solved it. Everything was pretty easy. Don't know is it a good decision and how fast it is. I have not found any other. So.. everything we need is define new BufferedImage.

BufferedImage buffImg = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffImg.createGraphics();

// ... other code we need

BufferedImage img= new BufferedImage(buffImg.getWidth(), buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(buffImg, 0, 0, null);
g2d.dispose();

If there any ideas to improve this method, please, your welcome.