java – 从图像中剥离Alpha通道

我想从PNG中剥离Alpha通道(透明背景),然后将它们写为JPEG图像.更准确地说,我想将透明像素设为白色.我尝试了两种技术,两种技术都以不同的方式失败:

方法1:

BufferedImage rgbCopy = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = rgbCopy.createGraphics();
graphics.drawImage(inputImage, 0, 0, Color.WHITE, null);
graphics.dispose();
return rgbCopy;

结果:图像具有粉红色背景.

方法2:

final WritableRaster raster = inputImage.getRaster();
final WritableRaster newRaster = raster.createWritableChild(0, 0, inputImage.getWidth(), inputImage.getHeight(), 0, 0, new int[]{0, 1, 2});
ColorModel newCM = new ComponentColorModel(inputImage.getColorModel().getColorSpace(), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
return new BufferedImage(newCM, newRaster, false, null);

结果:图像为黑色背景.

在这两种情况下,输入图像都是PNG,输出图像写为JPEG,如下所示:ImageIO.write(bufferedImage,“jpg”,buffer).如果它是相关的:这是在Java 8上,我使用12monkeys库来调整图像大小,然后再将其写为JPEG.

我已经尝试了上面代码的一些变体,没有运气.以前的一些问题提出了上述代码,但在这种情况下似乎并没有起作用.

最佳答案
感谢Rob的回答,我们现在知道为什么颜色混乱了.

问题是双重的:

> ImageIO用于编写JPEG的默认JPEGImageWriter,不会以其他软件理解的方式编写带有alpha的JPEG(这是一个已知问题).
>当将null作为目标传递给ResampleOp.filter(src,dest)并且过滤器方法是FILTER_TRIANGLE时,将创建一个新的BufferedImage,其中包含alpha(实际上是BufferedImage.TYPE_INT_ARGB).

重新采样后剥离alpha将起作用.但是,还有另一种方法可能更快并节省一些内存.也就是说,不是传递空目标,而是传递适当大小和类型的BufferedImage:

public static void main(String[] args) throws IOException {
    // Read input
    File input = new File(args[0]);
    BufferedImage inputImage = ImageIO.read(input);

    // Make any transparent parts white
    if (inputImage.getTransparency() == Transparency.TRANSLUCENT) {
        // NOTE: For BITMASK images, the color model is likely IndexColorModel,
        // and this model will contain the "real" color of the transparent parts
        // which is likely a better fit than unconditionally setting it to white.

        // Fill background  with white
        Graphics2D graphics = inputImage.createGraphics();
        try {
            graphics.setComposite(AlphaComposite.DstOver); // Set composite rules to paint "behind"
            graphics.setPaint(Color.WHITE);
            graphics.fillRect(0, 0, inputImage.getWidth(), inputImage.getHeight());
        }
        finally {
            graphics.dispose();
        }
    }

    // Resample to fixed size
    int width = 100;
    int height = 100;

    BufferedImageOp resampler = new ResampleOp(width, height, ResampleOp.FILTER_TRIANGLE);

    // Using explicit destination, resizedImg will be of TYPE_INT_RGB
    BufferedImage resizedImg = resampler.filter(inputImage, new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB));

    // Write output as JPEG
    ImageIO.write(resizedImg, "JPEG", new File(input.getParent(), input.getName().replace('.', '_') + ".jpg"));
}

转载注明原文:java – 从图像中剥离Alpha通道 - 代码日志