为什么我的BufferedImage绘制到画布上时不同?

问题描述 投票:4回答:1

原始

https://drive.google.com/file/d/1B3xxfWkGsMs2_MQ_bUQ8_ALYI0DL-LIo/view?usp=sharing

保存到文件时

https://drive.google.com/file/d/1z5euXupeHmiFebch4A39fVqGukoUiK0p/view?usp=sharing

打印到画布上时

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);

由于某些原因,如果我将图像打印到画布上,则与将同一图像保存到文件中不同。当我将其保存到文件中时,它会正确计算subImage,但是当我将其打印到画布上时,它会忽略我给定的x和y坐标,并使用给定宽度的(0,0)作为(x,y)来获取subImage和高度。

java javafx bufferedimage
1个回答
3
投票

documentation of the getSubimage method

返回由指定矩形区域定义的子图像。返回的BufferedImage与原始图像共享相同的数据数组。

子图像只是原始图像的“窗口”;他们使用相同的像素数据。

SwingFXUtils.toFXImage documentation状态:

快照指定的BufferedImage,并将其像素的副本存储到JavaFX Image对象中,如果需要,则创建一个新对象。

虽然只复制源图像尺寸中的像素当然是有意义的,但是上述词语并不能完全清楚地表明它不会复制整个像素数据缓冲区,从而忽略了子图像的边界。我认为这是一个错误,但我可以看到哪里可能有一个不是的论点。

同时,您可以通过自己提取子图像来解决此问题:

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);
© www.soinside.com 2019 - 2024. All rights reserved.