我正在尝试编辑新缓冲图像的像素,但是当我使用构造函数进行新的BufferedImage时,它不会显示,当我加载图像并设置像素时。为什么不显示?
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = 1000;
int h = 1000;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//ImageIO.read(new File("/Users/george/Documents/Ali.png"));
int color = Color.BLACK.getRGB();
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
image.setRGB(x, y, color);
}
}
g.drawImage(image, 0, 0, null);
}
答案 0 :(得分:3)
同样,不要在paintComponent中编辑BufferedImage - 在别处执行。例如:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ImageEdit extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int COLOR = Color.BLACK.getRGB();
private BufferedImage image = null;
public ImageEdit() {
image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_RGB);
for(int x = 0; x < PREF_H; x++) {
for(int y = 0; y < PREF_W; y++) {
image.setRGB(x, y, COLOR);
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
ImageEdit mainPanel = new ImageEdit();
JFrame frame = new JFrame("ImageEdit");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}