I wanna change different pixel to different color. Basically, change part of pixel to transparent.
for(int i = 0; i < image.getWidth();i++)
for(int j = 0; j < image.getHeight(); j ++)
{
image.setRGB(i,j , 0);
}
//I aslo change the third parameter 0 to another attribute. but it still does not work. it all show black. do you have some ideas?
yin. thanks
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);
}
}
The third parameter is ARGB value in 32 bits. This is laid out in bit form as:
AAAAAAAA|RRRRRRRR|GGGGGGGG|BBBBBBBBB
See the javadoc for BufferedImage.setRGB (assuming your using BufferedImage, your question doesn't actually say...)
Sets a pixel in this BufferedImage to the specified RGB value. The pixel is assumed to be in the default RGB color model, TYPE_INT_ARGB, and default sRGB color space. For images with an IndexColorModel, the index with the nearest color is chosen
You can create such a value using bit shifting.
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);
Luckily there is a getRGB() method on java.awt.Color instances, so you could use
image.setRGB(i, j, Color.green.getRGB());
Here's a full working example, perhaps you can compare to your code:
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);
}
}
Well, 3rd parameter is the color in RGB, so it will be black if you set it to 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With