Convert PNG to JPEG image in Java
This article shows how to convert an PNG image format to an JPEG image format in Java.
1. PNG Image
Below is a PNG image with a transparent background.
2. Java Convert PNG to JPEG
Since the JPEG image format doesn’t support the transparent background, we will create a white background as a replacement. Below is a complete Java example of converting a PNG image to a JPEG image.
Key information for BufferedImage
:
- JPEG needs
BufferedImage.TYPE_INT_RGB
- PNG needs
BufferedImage.TYPE_INT_ARGB
ConvertPngToJpg.java
package com.mkyong.io.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ConvertPngToJpg {
public static void main(String[] args) throws IOException {
Path source = Paths.get("C:\\test\\javanullpointer.png");
Path target = Paths.get("C:\\test\\new.jpg");
BufferedImage originalImage = ImageIO.read(source.toFile());
// jpg needs BufferedImage.TYPE_INT_RGB
// png needs BufferedImage.TYPE_INT_ARGB
// create a blank, RGB, same width and height
BufferedImage newBufferedImage = new BufferedImage(
originalImage.getWidth(),
originalImage.getHeight(),
BufferedImage.TYPE_INT_RGB);
// draw a white background and puts the originalImage on it.
newBufferedImage.createGraphics()
.drawImage(originalImage,
0,
0,
Color.WHITE,
null);
// save an image
ImageIO.write(newBufferedImage, "jpg", target.toFile());
}
}
A JPEG file with a white background.
The background can be any color, below snippet change the background to gray color.
newBufferedImage.createGraphics()
.drawImage(originalImage,
0,
0,
Color.GRAY,
null);
Further Reading
For more examples of BufferedImage
, please refer to this example – How to resize an image in Java
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Thanks, it works like a charm!
Hi,
I need the code to convert .gif image with transparent background to resized .jpg image ..I tried with different possibilities in the internet but no luck .I’m always getting the black image .please help me to resolve it.
Regards,
Satheesh
Just make sure you are not using
this : BufferedImage.TYPE_INT_ARGB
Thanks dude.
Hey thanks for sharing the source. Does this only work for small image conversions? What if you have a 2448×3264 PNG image (~13 MB) for converting to JPEG? Trying th code, it threw exception with Java out of memory error with heap space.
Then increase your memory for Java program.
Is there any library that use disk instead of memory. It will worst when server has many users concurrent .