6

jpg 画像を圧縮しようとすると、ほとんどの場合は完全に機能しますが、圧縮後に一部の jpg 画像が緑色に変わります。これが私のコードです

public void compressImage(String filename, String fileExtension) {
    BufferedImage img = null;
    try {
        File file = new File(filename);
        img = ImageIO.read(file);

        if (fileExtension.toLowerCase().equals(".png") || fileExtension.toLowerCase().equals(".gif")) {
            //Since there might be transparent pixel, if I dont do this,
            //the image will be all black.
            for (int x = 0; x < img.getWidth(); x++) {
                for (int y = 0; y < img.getHeight(); y++) {
                    int rgb = img.getRGB(x, y);
                    int alpha = (rgb >> 24) & 0xff;
                    if (alpha != 255) {
                        img.setRGB(x, y, -1); //set white
                    }
                }
            }
        }
        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        //Then, choose the first image writer available
        ImageWriter writer = (ImageWriter) iter.next();
        //instantiate an ImageWriteParam object with default compression options
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        //Set the compression quality
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(0.8f);
        //delete the file. If I dont the file size will stay the same
        file.delete();
        ImageOutputStream output = ImageIO.createImageOutputStream(new File(filename));
        writer.setOutput(output);
        IIOImage image = new IIOImage(img, null, null);
        writer.write(null, image, iwp);
        writer.dispose();
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, ioe.getMessage());
    }
}

元の画像 画像を圧縮します。 画像が緑色に変わります

4

3 に答える 3

0

経験から、緑はフォーマットされたばかりの YUV メモリ (特に YV12) の色であることがわかっています。だから私の推測では、いくつかのステップが失敗していて、ルミナンス情報を取得しますが、クロマは失敗します. Cr面に到達する前に失敗しているように見えます。

とにかく、頑張ってください、それは大変なことです。あなたのコードは奇妙に見えますが、上部にある変な png 固有のコードは何ですか? 私の知る限り、.NET を使用している場合は、登録済みの画像形式を、面白い作業のない画像であるかのように扱うことができます。

于 2011-04-06T03:32:06.000 に答える