gpt4 book ai didi

Java图像被剪切

转载 作者:行者123 更新时间:2023-12-02 06:03:16 25 4
gpt4 key购买 nike

我的画有一点问题。我使用以下方法加载图像:

public Image getImage(String name) {
Image image = (Image) this.storage_images.get(name);

if((image == null) && (!name.endsWith("-"))) {
try {
InputStream stream = this.getClass().getResourceAsStream(name);

if(stream != null) {
byte[] image_bytes = new byte[stream.available()];
stream.read(image_bytes);
image = Toolkit.getDefaultToolkit().createImage(image_bytes);
}
} catch (Exception exception) {
System.err.println("Unable to read image from JAR.");
}

if(image == null) {
try {
image = this.client.getImage(this.client.getCodeBase(), name);
} catch (Exception exception) {
System.out.println("ERROR: while receiving image(" + name + "): " + exception);
}
}

if(image != null) {
this.client.prepareImage(image, null);
this.storage_images.put(name, image);
}
}

return image;
}

当我绘制图像时,它会被剪切 - 奇怪的是。我只改变与高度的比例。原始图像的尺寸为 256x256。

问题是这样的:在appletviewer(eclipse)上它似乎是正确的。但是当我编译它并通过网络浏览器打开它时,图像将被剪切(请参见底部的屏幕截图)。

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

new int[] {
40, // position left
10, // position top
65, // width (Original is 256)
65 // height (Original is 256)
};
g2.drawImage(getImage("warning.png"), insets.right + data[0], insets.bottom + data[1], data[2], data[3], null);
}

我希望你能告诉我,我做错了什么。

网络浏览器上的结果

Webbrowser

Eclipse IDE 中 AppletViewer 的结果*

AppletViewer

最佳答案

问题就在这里。

byte[] image_bytes  = new byte[stream.available()];

可用值不是完整图像大小,而是保证下次读取时可用的字节数。

但无论如何,这些废话都是不必要的。大多数可以加载图像的方法都会被重载以接受 InputStream

进一步说明

g2.drawImage(
getImage("warning.png"),
insets.right + data[0],
insets.bottom + data[1],
data[2],
data[3],
null);

应该是:

g2.drawImage(
getImage("warning.png"),
insets.right + data[0],
insets.bottom + data[1],
data[2],
data[3],
this);

对于比“可能”更好的内容,请发布 MCTaRE (最小的完整测试和可读示例)。

关于Java图像被剪切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22505208/

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