使用Java进行图像转码(JPEG到PNG)

22

在我的Java应用程序中,我想下载一个JPEG文件,将它转换成PNG格式,并对生成的字节进行一些处理。

我几乎确定记得有一个库可以实现这个功能,但我不记得它的名字了。

4个回答

40

这就是我最终所做的,当我提出问题时,我的思路跑得太远了。

// 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();

3
代码示例在这里非常有用。很高兴不必将其写入新文件中。 - clay

15

javax.imageio 应该足够使用。将您的JPEG转换成BufferedImage,然后使用以下方式保存:

File file = new File("newimage.png");
ImageIO.write(myJpegImage, "png", file);

15

ImageIO 可以用于加载 JPEG 文件并保存为 PNG 文件(也可以保存到 ByteArrayOutputStream,如果您不想写入文件)。


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);
}

这个回答与问题不符。OP要求将JPG转换为PNG,而不是反过来... - Cardin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接