【问题标题】:Why is my BufferedImage different when drawn to canvas?为什么绘制到画布时我的 BufferedImage 不同?
【发布时间】:2019-12-20 15:21:53
【问题描述】:

原创

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】:

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

    【讨论】:

    • 前段时间看了一个类似的问题,研究了SwingFXUtils的源码。我还得出结论,这是一个错误。我没有看到任何当前行为有用的用例......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2014-08-15
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多