22

In my Java application I would like to download a JPEG, transfer it to a PNG and do something with the resulting bytes.

I am almost certain I remember a library to do this exists, I cannot remember its name.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
adam
  • 22,404
  • 20
  • 87
  • 119

4 Answers4

40

This is what I ended up doing, I was thinking toooo far outside of the box when I asked the question..

// these are the imports needed
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;

// read a jpeg from a inputFile
BufferedImage bufferedImage = ImageIO.read(new File(inputFile));

// write the bufferedImage back to outputFile
ImageIO.write(bufferedImage, "png", new File(outputFile));

// this writes the bufferedImage into a byte array called resultingBytes
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOut);
byte[] resultingBytes = byteArrayOut.toByteArray();
Hat
  • 540
  • 8
  • 25
adam
  • 22,404
  • 20
  • 87
  • 119
15

javax.imageio should be enough. Put your JPEG to BufferedImage, then save it with:

File file = new File("newimage.png");
ImageIO.write(myJpegImage, "png", file);
bezmax
  • 25,562
  • 10
  • 53
  • 84
15

ImageIO can be used to load JPEG files and save PNG files (also into a ByteArrayOutputStream if you don't want to write to a file).

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
1
BufferedImage bufferGambar;
try {

    bufferGambar = ImageIO.read(new File("ImagePNG.png"));
    // pkai type INT karna bertipe integer RGB bufferimage
    BufferedImage newBufferGambar = new BufferedImage(bufferGambar.getWidth(), bufferGambar.getHeight(), BufferedImage.TYPE_INT_RGB);

    newBufferGambar.createGraphics().drawImage(bufferGambar, 0, 0, Color.white, null);
    ImageIO.write(newBufferGambar, "jpg", new File("Create file JPEG.jpg"));

    JOptionPane.showMessageDialog(null, "Convert to JPG succes YES");

} catch(Exception e) {
    JOptionPane.showMessageDialog(null, e);
}
bfontaine
  • 18,169
  • 13
  • 73
  • 107
waviq
  • 29
  • 1
  • This answer doesn't match the question. OP asked for JPG to PNG, not the other way round... – Cardin Aug 27 '18 at 09:06