Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PNG into JPEG

I'm having problems converting a simple PNG into a JPEG format. I'm using the following code:

...

    File png = new File(filePath);
    try {
        SeekableStream s = new FileSeekableStream(png);
        PNGDecodeParam pngParams = new PNGDecodeParam();
        ImageDecoder dec = ImageCodec.createImageDecoder("png", s, pngParams);
        RenderedImage pngImage = dec.decodeAsRenderedImage();
        JPEGEncodeParam jparam = new JPEGEncodeParam();
        jparam.setQuality(0.50f); // e.g. 0.25f
        File jpeg = new File("jpeg.jpeg");
        FileOutputStream out = new FileOutputStream(jpeg);

        ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, jparam); 

        encoder.encode(pngImage);

        s.close();

    } catch (IOException e) {
        ok = false;
        e.printStackTrace();
    }

    return ok;
}

...

I end up with an JAI exception -> java.lang.RuntimeException: Only 1, or 3-band byte data may be written. at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:148) ...

Ran out of options. Any suggestion?

like image 656
Norberto Avatar asked Feb 18 '10 16:02

Norberto


People also ask

How do I convert multiple PNG to JPG?

Go to File>Automate>Batch. Choose the created set and action, and select the PNG images you want to convert. Photoshop will bulk convert all PNG images to JPEG on your Windows.

How do I change a PNG to a JPG in Windows?

Converting an Image With WindowsOpen the image you want to convert into PNG by clicking File > Open. Navigate to your image and then click “Open.” Once the file is open, click File > Save As. In the next window make sure you have PNG selected from the drop-down list of formats, and then click “Save.”

How do I convert an image to JPEG?

Click the “File” menu and then click the “Save As” command. In the Save As window, choose the JPG format on the “Save As Type” drop-down menu and then click the “Save” button.


2 Answers

It might be easier to use ImageIO to read the PNG into a BufferedImage and write the image out in JPEG format.

Addendum: In this approach, the conversion is handled transparently by the writer's ImageTranscoder.

BufferedImage img = ImageIO.read(new File("image.png"));
ImageIO.write(img, "jpg", new File("image.jpg"));
like image 148
trashgod Avatar answered Oct 02 '22 13:10

trashgod


you probably have alpha channel in the png that you need to get rid of before trying to write the jpg.

Create a new BufferedImage with type TYPE_INT_RGB (not TYPE_INT_ARGB), and then write your source image (pngImage) onto the new blank image.

Something like this (warning, not tested code):

BufferedImage newImage = new BufferedImage( pngImage.getWidth(), pngImage.getHeight(), BufferedImage.TYPE_INT_RGB);
newImage.createGraphics().drawImage( pngImage, 0, 0, Color.BLACK, null);
like image 27
Trevor Harrison Avatar answered Oct 02 '22 13:10

Trevor Harrison