Java Image是切割的

时间:2014-03-19 12:01:45

标签: java image paintcomponent japplet

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

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)上似乎是正确的。但是当我编译它并在我的webbrowser上打开它时,图像将被切割(参见底部的屏幕截图)。

@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上的结果

Webbrowser

eclipse IDE *中的AppletViewer结果

AppletViewer

2 个答案:

答案 0 :(得分:2)

这是问题所在。

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(最小完整测试和可读示例)。

答案 1 :(得分:0)

噢,问题解决了。

位于图片本身!