简体   繁体   English

使具有特定颜色的图像的每个像素透明

[英]Making every pixel of an image having a specific color transparent

This question is a duplicate of this question: Making every pixel of an image having a specific color transparent 这个问题是这个问题的重复: 使具有特定颜色的图像的每个像素透明

But I need a Java equivalent. 但是我需要一个等效的Java。 And I need a image-type (like PNG , BMP , ...) which can hold this color with full transparency (alpha = 0). 而且我需要一个图像类型(例如PNGBMP等),它可以完全透明(alpha = 0)保存这种颜色。 And of course a way to save it as a file. 当然还有一种将其保存为文件的方法。

import java.awt.*;
import java.awt.image.*;

public class Transparency {
  public static Image makeColorTransparent
    (Image im, final Color color) {
    ImageFilter filter = new RGBImageFilter() {
      // the color we are looking for... Alpha bits are set to opaque
      public int markerRGB = color.getRGB() | 0xFF000000;

      public final int filterRGB(int x, int y, int rgb) {
        if ( ( rgb | 0xFF000000 ) == markerRGB ) {
          // Mark the alpha bits as zero - transparent
          return 0x00FFFFFF & rgb;
          }
        else {
          // nothing to do
          return rgb;
          }
        }
      }; 

    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
    }
}

Modified the code to make each pixel transparent 修改代码以使每个像素透明

Source :http://www.rgagnon.com/javadetails/java-0265.html 来源:http://www.rgagnon.com/javadetails/java-0265.html

Use ImageIO.read for reading a file and ImageIO.write for writing. 使用ImageIO.read读取文件,使用ImageIO.write写入。 Use the getRGB and setRGB methods of BufferedImage to change the colours. 使用BufferedImagegetRGBsetRGB方法更改颜色。

You can use a LookupOp with a four-component LookupTable that sets the alpha component to zero for colors that match the background. 您可以使用一个LookupOp有四组分LookupTable ,设置的alpha分量为零匹配背景颜色。 Examples may be found in Using the Java 2D LookupOp Filter Class to Process Images and Image processing with Java 2D . 使用Java 2D LookupOp过滤器类处理图像使用Java 2D进行图像处理中可以找到示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM