java - 在小程序中将图像转换为缓冲图像

标签 java image swing applet imageicon

我尝试了很多方法在小程序中将 Image 类的图像转换为 BufferedImage。我得到了一种方法,该方法在从 netbeans 运行时工作正常,但在通过浏览器运行时相同的代码无法工作。我尝试过的代码是

ImageIcon icon = new ImageIcon(orgImage);
BufferedImage buffer = ((ToolkitImage) icon.getImage()).getBufferedImage();

还尝试了以下方法

1) BufferedImage buffer = ((ToolkitImage) orgImage).getBufferedImage();

2) BufferedImage  buffer = new BufferedImage(
   orgImage.getWidth(null), orgImage.getWidth(null), BufferedImage.TYPE_INT_RGB);
   buffer.getGraphics().drawImage(orgImage, 0, 0, null);

orgImage 是彩色图像。

在所有这些情况下缓冲区均为空..

我的问题的解决方案是什么?

最佳答案

要将图像转换为缓冲图像,您可以使用以下函数:

/**
 * Converts a given Image into a BufferedImage
 * 
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public BufferedImage toBufferedImage(Image img){
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();
    // Return the buffered image
    return bimage;
}

将其粘贴到类中的任意位置并使用以下代码:

BufferedImage bi = toBufferedImage(orgImage);

~问候麦克斯

关于java - 在小程序中将图像转换为缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602972/

相关文章:

java - 在 JTree 中获取一个节点

java - Source Sans Pro 的 TTF 和 OTF 版本在 Swing (Nimbus L&F) 中的显示方式不同

java - 如何使用 JUNG 对绘图边缘进行动画处理

java - 作为模式属性传递时,正则表达式不起作用

java - XMLInputFactory 是线程安全的吗?

python - Pygame:通过网络发送图像 PodSixNet

html - 如何将图像放在div的顶部?

java - 尝试使用 JAVA 启动 Pig 脚本时出错

java - 更改 ListView 中所有列表项的字体

image - Bing/Google/Flickr API:您将如何查找包含15万个日语句子的图像?