更改图像java中每个像素的颜色

Hua*_*Yin 4 java

我想将不同的像素改为不同的颜色.基本上,将像素的一部分更改为透明.

for(int i = 0; i < image.getWidth();i++)
        for(int j = 0; j < image.getHeight(); j ++)
        {
            image.setRGB(i,j , 0);
        }
Run Code Online (Sandbox Code Playgroud)

//我还将第三个参数0更改为另一个属性.但它仍然无效.它都显示黑色.你有什么想法吗?

阴.谢谢

class ImagePanel extends JPanel {

    private BufferedImage image;

    public ImagePanel(int width, int height, BufferedImage image) {
        this.image = image;
        image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        repaint();
    }

    /**
     * Draws the image.
     */

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                image.setRGB(i, j, 0);
            }
        }
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);

    }

}
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 8

第三个参数是32位的ARGB值.这是以位形式列出的:

AAAAAAAA|RRRRRRRR|GGGGGGGG|BBBBBBBBB
Run Code Online (Sandbox Code Playgroud)

请参阅BufferedImage.setRGB的javadoc (假设您使用BufferedImage,您的问题实际上并没有说......)

将此BufferedImage中的像素设置为指定的RGB值.假设像素位于默认的RGB颜色模型TYPE_INT_ARGB和默认的sRGB颜色空间中.对于具有IndexColorModel的图像,选择具有最近颜色的索引

  • 如果您使用的是支持透明度的图像类型,则设置alpha 255表示完全不透明,0表示完全透明非常重要.

您可以使用位移创建这样的值.

int alpha = 255; 
int red   = 0;
int green = 255;
int blue  = 0;

int argb = alpha << 24 + red << 16 + green << 8 + blue

image.setRGB(i, j, argb);
Run Code Online (Sandbox Code Playgroud)

幸运的是,java.awt.Color实例上有一个getRGB()方法,所以你可以使用

image.setRGB(i, j, Color.green.getRGB());
Run Code Online (Sandbox Code Playgroud)

这是一个完整的工作示例,也许您可​​以与您的代码进行比较:

public class StackOverflow27071351 {
    private static class ImagePanel extends JPanel {
        private BufferedImage image;
        public ImagePanel(int width, int height, BufferedImage image) {
            this.image = image;
            image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_ARGB);
            repaint();
        }
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0; i < image.getWidth(); i++) {
                for (int j = 0; j < image.getHeight(); j++) {
                    image.setRGB(i, j, new Color(255, 0, 0, 127).getRGB());
                }
            }
            g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        int width = 640;
        int height = 480;
        frame.setSize(width, height);
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(new ImagePanel(width, height, image));
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)