Reputation: 39
Short Question: Is it possible to color an image directly in the graphics2d.drawImage(...) method? I mean not to choose the background color but select a color for every visible pixel on the image.
Upvotes: 0
Views: 342
Reputation: 18792
Here is an example of manipulating pixels of a BufferedImage
.
The example inverts this image
to negative by manipulating each pixel:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ShowNegativeImage {
public static void main(String[] args) {
BufferedImage bImage = getImage("http://www.digitalphotoartistry.com/rose1.jpg");
image2Negative(bImage);
displayImage(bImage);
}
private static BufferedImage getImage(String path) {
URL url = null;
try {
url = new URL(path);
return ImageIO.read(url);
} catch ( IOException ex) { ex.printStackTrace();}
return null;
}
private static void displayImage(java.awt.Image image){
ImageIcon icon= new ImageIcon(image);
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel(icon));
frame.pack();
frame.setVisible(true);
}
private static void image2Negative(BufferedImage bImage) {
for (int x = 0; x < bImage.getWidth(); x++) {
for (int y = 0; y < bImage.getHeight(); y++) {
int rgba = bImage.getRGB(x, y);
Color col = new Color(rgba, true);
col = new Color(255 - col.getRed(),
255 - col.getGreen(),
255 - col.getBlue());
bImage.setRGB(x, y, col.getRGB());
}
}
}
}
Output:
Upvotes: 1