【问题标题】:Image transcoding (JPEG to PNG) with Java使用 Java 进行图像转码(JPEG 到 PNG)
【发布时间】:2010-09-26 06:39:09
【问题描述】:

在我的 Java 应用程序中,我想下载 JPEG,将其转换为 PNG,然后对生成的字节进行处理。

我几乎可以肯定我记得存在一个这样做的库,我不记得它的名字。

【问题讨论】:

    标签: java png jpeg image-transcoding


    【解决方案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 文件(如果您不想写入文件,也可以使用 ByteArrayOutputStream)。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:
        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,而不是相反...
        猜你喜欢
        • 2021-09-06
        • 2015-01-16
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 1970-01-01
        • 2012-10-14
        • 2014-01-11
        • 1970-01-01
        相关资源
        最近更新 更多