Convert PNG to JPG Image file using Java
This example demonstrates how to convert PNG
to JPG
image file using Java. You can expect some quality loss when converting images to/from PNG
/JPG
. PNG
supports transparent background. JPG
does not support transparent background. We can overcome this limitation by replacing the transparent background with a default background color.
Convert PNG to JPG
We can obtain a BufferedImage
by using the ImageIO.read()
method.
Next, we create a new BufferedImage
with the same dimensions as the original and most impotently we pass in the BufferedImage.TYPE_INT_RGB
. This represents an image with 8-bit
RGB
color components packed into integer pixels.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ConvertPngToJpg {
public static void main(String... args) {
try {
File input = new File("/tmp/duke.png");
File output = new File("/tmp/duke-to-jpg.jpg");
BufferedImage image = ImageIO.read(input);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB);
result.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
ImageIO.write(result, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Replace PNG Transparent Background Color
We can replace the PNG
transparent color with a default background color using the BufferedImage.createGraphics().drawImage()
method. We can pass any color in the fourth argument which’ll be used to replace the transparent color of PNG
.
...
BufferedImage image = ImageIO.read(input);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB);
result.createGraphics().drawImage(image, 0, 0, Color.PINK, null);
ImageIO.write(result, "jpg", output);
...
Converted Images
To demonstrate the result, we added the following table.
duke.png (original) | duke-to-jpg.jpg | duke-to-jpg-pink-bg.jpg |
---|---|---|
Background: transparent | Background: white | Background: pink |
Size: 9KB | Size: 12KB | Size: 13KB |