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

2022-09-02 02:18:23

在我的Java应用程序中,我想下载JPEG,将其传输到PNG,然后对生成的字节执行某些操作。

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


答案 1

这就是我最终所做的,当我问这个问题时,我跳得太远了。

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

答案 2

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


推荐