为什么我的 BufferedImage 在绘制到 canvas 时不同?
Why is my BufferedImage different when drawn to canvas?
原创
https://drive.google.com/file/d/1B3xxfWkGsMs2_MQ_bUQ8_ALYI0DL-LIo/view?usp=sharing
保存到文件时
https://drive.google.com/file/d/1z5euXupeHmiFebch4A39fVqGukoUiK0p/view?usp=sharing
当打印到canvas
https://drive.google.com/file/d/1VouD-ygf0pPXFFx9Knr4pv44FHMtoqcV/view?usp=sharing
BufferedImage temp = bImg.getSubimage(100, 100, (int)imgWidth - 100, (int)imgHeight - 100);
try{
ImageIO.write(temp, "png", new File("test.png"));
}catch(Exception e){
e.printStackTrace();
}
gc.drawImage(SwingFXUtils.toFXImage(temp, null), 100, 100);
出于某种原因,如果我将图像打印到 canvas,这与将同一图像保存到文件是不同的。当我将它保存到一个文件时,它会正确计算子图像,但是当我将它打印到 canvas 时,它会忽略我给它的 x 和 y 坐标,并使用 (0,0) 作为 (x,y)具有给定的宽度和高度。
来自documentation of the getSubimage method:
Returns a subimage defined by a specified rectangular region. The returned BufferedImage
shares the same data array as the original image.
子图只是原图的“window”;他们使用相同的像素数据。
SwingFXUtils.toFXImage documentation 状态:
Snapshots the specified BufferedImage
and stores a copy of its pixels into a JavaFX Image
object, creating a new object if needed.
虽然只复制源图像尺寸中的像素当然有意义,但上面的话并没有完全清楚它不会复制整个像素数据缓冲区,因此忽略了边界子图像。我会认为这是一个错误,但我可以看到哪里可能有争论说它不是。
同时,您可以通过自己提取子图像来解决此问题:
BufferedImage cropped = new BufferedImage(
(int) imgWidth - 100,
(int) imgHeight - 100,
bImg.getType());
Graphics g = cropped.getGraphics();
g.drawImage(bImg, -100, -100, null);
g.dispose();
gc.drawImage(SwingFXUtils.toFXImage(cropped, null), 100, 100);
原创
https://drive.google.com/file/d/1B3xxfWkGsMs2_MQ_bUQ8_ALYI0DL-LIo/view?usp=sharing
保存到文件时
https://drive.google.com/file/d/1z5euXupeHmiFebch4A39fVqGukoUiK0p/view?usp=sharing
当打印到canvas
https://drive.google.com/file/d/1VouD-ygf0pPXFFx9Knr4pv44FHMtoqcV/view?usp=sharing
BufferedImage temp = bImg.getSubimage(100, 100, (int)imgWidth - 100, (int)imgHeight - 100);
try{
ImageIO.write(temp, "png", new File("test.png"));
}catch(Exception e){
e.printStackTrace();
}
gc.drawImage(SwingFXUtils.toFXImage(temp, null), 100, 100);
出于某种原因,如果我将图像打印到 canvas,这与将同一图像保存到文件是不同的。当我将它保存到一个文件时,它会正确计算子图像,但是当我将它打印到 canvas 时,它会忽略我给它的 x 和 y 坐标,并使用 (0,0) 作为 (x,y)具有给定的宽度和高度。
来自documentation of the getSubimage method:
Returns a subimage defined by a specified rectangular region. The returned
BufferedImage
shares the same data array as the original image.
子图只是原图的“window”;他们使用相同的像素数据。
SwingFXUtils.toFXImage documentation 状态:
Snapshots the specified
BufferedImage
and stores a copy of its pixels into a JavaFXImage
object, creating a new object if needed.
虽然只复制源图像尺寸中的像素当然有意义,但上面的话并没有完全清楚它不会复制整个像素数据缓冲区,因此忽略了边界子图像。我会认为这是一个错误,但我可以看到哪里可能有争论说它不是。
同时,您可以通过自己提取子图像来解决此问题:
BufferedImage cropped = new BufferedImage(
(int) imgWidth - 100,
(int) imgHeight - 100,
bImg.getType());
Graphics g = cropped.getGraphics();
g.drawImage(bImg, -100, -100, null);
g.dispose();
gc.drawImage(SwingFXUtils.toFXImage(cropped, null), 100, 100);