gpt4 book ai didi

java - Graphics.drawImage 将 BufferedImage 留空

转载 作者:行者123 更新时间:2023-11-30 07:45:27 25 4
gpt4 key购买 nike

我正在尝试提取 BufferedImage 的 10 px 方形部分并将它们添加到新的 BufferedImage 中,与 this drawImage tutorial 中显示的困惑示例非常相似。但是,我的 BufferedImage 调用后似乎仍为空。如果我调用drawString,我会看到字符串被正常绘制。

Graphics.drawImage 的文档中,有这样的说法

This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false. As more of the image becomes available, the process that loads the image notifies the specified image observer.

我需要一个ImageObserver来等待输出吗?如果是这样我应该使用什么实现类?如果不是,正确的解决方案是什么?

MCVE

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class TestImageScale {

public static void main(String[] args) throws IOException {
BufferedImage img = ImageIO.read(new File(
"example.jpeg"));

//Randomly generate some coordinates to grab pixels from
int minDim = Math.min(img.getHeight(), img.getWidth()) - 10;
int[][] coordMatch = new int[5][3];
for (int i = 0; i < 5; i++) {
coordMatch[i][0] = (int) Math.floor(Math.random() * minDim + 5);
coordMatch[i][1] = (int) Math.floor(Math.random() * minDim + 5);
coordMatch[i][2] = 5;
}

BufferedImage simImg = new BufferedImage(10, 10 * 5, BufferedImage.TYPE_INT_ARGB);
Graphics g = simImg.getGraphics();

for (int i = 0; i < 5; i++) {
int x = coordMatch[i][0];
int y = coordMatch[i][1];
int r = coordMatch[i][2];
//Print statement to show that we are in the for loop
System.out.println(String.format("%s,%s,%s", x, y, r));
//g.drawImage should write the pixels from img to simImg
g.drawImage(img, x - r, y - r, x + r, y + r, 0, i * 10, 10, i * 10 + 10, null);
}
//I draw the string "hello" on simImg to show that g is working
g.drawString("hello", 0, 10);

ImageIO.write(simImg, "png", new File("output.png"));
}


}

在测试运行中,我得到了这些行

322,228,5
118,186,5
285,351,5
21,213,5
144,48,5

打印到控制台,保存的文件看起来像

Example output showing start of printed string "hello"

此输出显示已进入 for 循环,并且 Graphics 对象 g 连接到正确的 BufferedImage。但 img 中的像素不会复制到 simImg

根据要求,来自 Matlab 演示图像的用于测试的示例图像。但实际上,我测试过的每张图像都是如此。 example.png

最佳答案

我认为您的 drawImage 的一些参数顺序错误。

Javadoc for the drawImage method you are using提到目标矩形的坐标位于源矩形的坐标之前。在我看来,您好像首先使用源坐标,然后使用目标坐标来调用此方法。

而不是

        g.drawImage(img, x - r, y - r, x + r, y + r, 0, i * 10, 10, i * 10 + 10, null);

尝试

        g.drawImage(img, 0, i * 10, 10, i * 10 + 10, x - r, y - r, x + r, y + r, null);

我没有你的测试图像,所以我使用了另一张图像。进行此修改并运行您的类后,我得到了一个并非完全空白的输出图像,并且看起来已经从我的示例图像中复制了像素。

关于java - Graphics.drawImage 将 BufferedImage 留空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com