Gwalk Gwalk - 1 year ago 216
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
byte[] newImage = byteStream.toByteArray();

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

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 Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download