Ionut Ungureanu
Ionut Ungureanu

Reputation: 380

Java PNG to JPG Bug

I am trying to convert a PNG image to a JPEG image following this tutorial. But I encounter a problem. The resulting image has a pink layer.

Does anyone have a solution for this problem? Or what code should I use in order to convert the image into the desired format?

Thanks in advance!

Upvotes: 1

Views: 1985

Answers (2)

Dipin Narayanan
Dipin Narayanan

Reputation: 1105

Which color mode are you using? While you create buffered image object, try adding the type like this option.

    File newFile = new File(path + fileName + "." + Strings.FILE_TYPE);

    Image image = null;
    try {
        image = ImageIO.read(url); // I was using an image from web
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    try {
        BufferedImage img = toBufferedImage(image);
        ImageIO.write(img, "jpg", newFile);
    } catch (IOException e) {
        e.printStackTrace();
    }



}

private static BufferedImage toBufferedImage(Image src) {
    int w = src.getWidth(null);
    int h = src.getHeight(null);
    int type = BufferedImage.TYPE_INT_RGB; // other options
    BufferedImage dest = new BufferedImage(w, h, type);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(src, 0, 0, null);
    g2.dispose();
    return dest;
}

Upvotes: 4

Dmitry Negoda
Dmitry Negoda

Reputation: 3189

  1. Create a BufferedImage of desired size, e.g.:

    BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB)

  2. fill it with a proper background color:

    img.getGraphics().fillRect(....)

  3. Call drawImage on the image's graphics atop of that background:

    img.getGraphics().drawImage(image, 0, 0, null);

then write down your image as JPG as usual.

Upvotes: 4

Related Questions