Skip to main content

Converting from png to jpg

1 reply [Last post]
olle
Offline
Joined: 2006-08-01

Hi I have a problem.
I’m writing an app that would like to convert png images to jpg. It works fine but transparent areas become gray, is there any possibility to make that gray into white? I user the following code (I’m also rescaling the image). For some reasons I must just Java 1.3.

Best reagards
Olle

imageData is byte[]

Image inImage = new ImageIcon(imageData).getImage();
double scale = (double) maxDim / (double) inImage.getHeight(null);

int scaledW = (int) (scale * inImage.getWidth(null));
int scaledH = (int) (scale * inImage.getHeight(null));
BufferedImage outImage = new BufferedImage(scaledW, scaledH,BufferedImage.TYPE_INT_RGB);
AffineTransform tx = new AffineTransform();

if (scale < 1.0d) {
tx.scale(scale, scale);
}

Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(inImage, tx, null);
g2d.dispose();

OutputStream os = new FileOutputStream(thumb);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
os.close();

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
bae
Offline
Joined: 2005-03-02

Hi Olle,

it looks like you just need to fill background area
with wite color before calling drawImage:

Graphics2D g2d = outImage.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, outImage.getWidth(), outImage.getHeight());
g2d.drawImage(inImage, tx, null);
g2d.dispose();

Thanks,
Andrew.