[英]Swing Graphics color Image directly
Short Question: Is it possible to color an image directly in the graphics2d.drawImage(...) method? 简短的问题:是否可以直接在graphics2d.drawImage(...)方法中为图像着色? I mean not to choose the background color but select a color for every visible pixel on the image. 我的意思是不选择背景颜色,而是为图像上的每个可见像素选择一种颜色。
Here is an example of manipulating pixels of a BufferedImage
. 这是一个操作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: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.