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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/356616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:47:01  来源:igfitidea点击:

Image transcoding (JPEG to PNG) with Java

javapngjpegimage-transcoding

提问by adam

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

在我的 Java 应用程序中,我想下载一个 JPEG,将它传输到一个 PNG 并使用结果字节做一些事情。

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

我几乎可以肯定我记得有一个图书馆可以做到这一点,我不记得它的名字了。

采纳答案by Joachim Sauer

ImageIOcan be used to load JPEG files and save PNG files (also into a ByteArrayOutputStreamif you don't want to write to a file).

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

回答by bezmax

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

javax.imageio应该足够了。将您的 JPEG 放入 BufferedImage,然后将其保存为:

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

回答by adam

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

回答by waviq

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