问题
I'm new to Java graphics (computer graphics in general) and Stack Overflow, so please help me out and help me phrase my problem better.
At the moment, I'm trying to display a BufferedImage alongside the original image in a Java GUI. This is my code:
Image oriImage = robot.getQwerkController().getVideoStreamService().getFrame(); //load the original image
Graphics2D hi = bufferedImage.createGraphics();
hi.drawImage(oriImage, 0,0, null); //draw the original image into the BufferedImage
hi.dispose();
images[0].put(oriImage, 1); //draws the original image in the first frame
images[1].put(bufferedImage, 2); //draws the BufferedImage in the second frame
and the "put" function is as follows:
public synchronized void put(Image image, int frameNumber) {
icon.setImage(image); //sets the image displayed by this icon
display.paintImageIcon(icon, frameNumber); //paint the image onto the gui
imageSet = true;
notifyAll();
}
However, the resulting GUI is as follows
So the Image works, but BufferedImage doesn't. I'd assume it works because BufferedImage is a subclass of Image... Any idea? Please let me know if additional code is needed~ Thanks in advance :)
EDIT 1:
I did some testing, and instead of using the original image, I created an whole new bufferedImage, and used Graphics2D to draw a line and then try and display it. here is the result:
http://i.imgur.com/rJAdp.jpg
So it works. Therefore there must be something wrong with the original image (or the conversion that happened)
EDIT 2: I did a similar thing with bufferedImage and drew a line. The result are the same as EDIT 1, and therefore I think there's some problem with drawImage function.
EDIT 3: I fixed the problem by putting a while loop around the drawImage to let it complete the image drawing (because it returns false if it hasn't finish drawing an image yet) and it worked! :D
boolean x = false;
while (!x) {
x = hi.drawImage(oriImage, 0,0, null); //draw the original image into the BufferedImage
}
回答1:
You should be able to achieve the same result if you just pass the ImageObserver
(the JFrame
or JPanel
instance into which you're drawing) into the drawImage
method instead of null
. This will then take care of the asynchronous image loading for you.
回答2:
Sorry, but I guess you are using immediate painting (push). In general java does it the other way around (pull).
Java swing/awt draws event driven: one does not draw an image immediately, but one could trigger it by an invalidate or repaint. You could start a swing Timer with your frame rate and call there repaint().
In general a JPanel child might then override paintComponent(Graphics g)
and draw on g
.
Nevertheless it is weird. You might try logging oriImage.getHeight(null)
, to see (unlikely) whether the image is produced asynchroneously (height -1 at the beginning).
来源:https://stackoverflow.com/questions/11304208/bufferedimage-not-displaying-all-black-but-image-can-be-displayed