[英]How can I edit a BufferedImage after it has been displayed?
I'm working with a 16bit grayscale image: 我正在使用16位灰度图像:
BufferedImage bufferedImage = new BufferedImage(320, 240, BufferedImage.TYPE_USHORT_GRAY);
I'm able to edit that image by grabbing a reference to its underlying storage. 我可以通过获取对其底层存储的引用来编辑该图像。 The data is stored in a linear array, in row major order:
数据以行主要顺序存储在线性数组中:
short[] data = ((DataBufferUShort)bufferedImage.getRaster().getDataBuffer()).getData();
However, if bufferedImage
has been rendered to any screen, editing data
no longer has any effect.; 但是,如果
bufferedImage
已渲染到任何屏幕,则编辑data
将不再起作用。 I can edit the data before its displayed on the screen, but after displaying it I can no longer change it. 我可以在屏幕上显示数据之前对其进行编辑,但是在显示数据之后,我将无法再对其进行更改。
I've of course tried repainting the AWT control -- it didn't update with the new pixel data. 我当然尝试过重新绘制AWT控件-它没有使用新的像素数据进行更新。 I've even tried getDataElements & setDataElements.
我什至尝试了getDataElements和setDataElements。 Nothing seems to work, after the image has been displayed.
显示图像后,似乎没有任何反应。
I suspect there's something wrong with the way you're painting your image to the screen. 我怀疑您在屏幕上绘画图像的方式有问题。
Here's some minimal code that demonstrates what you're doing should work: 以下是一些最小的代码,这些代码演示了您正在执行的操作:
public class Test {
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
JFrame frame = new JFrame("Image Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_USHORT_GRAY);
ImageComponent component = new ImageComponent(image);
frame.add(component);
frame.pack();
frame.setVisible(true);
short gray = 0;
short[] data = ((DataBufferUShort) image.getRaster().getDataBuffer()).getData();
while (true) {
for (int i = 0; i < data.length; i++) {
data[i] = gray;
}
Thread.sleep(20);
gray += 1000;
component.repaint();
}
}
static class ImageComponent extends JComponent {
private BufferedImage image;
public ImageComponent(BufferedImage image) {
this.image = image;
this.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.