本文介绍了错误:sun.awt.image.ToolkitImage 无法转换为 java.awt.image.BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我不能做这件事来对我工作 sun.awt.image.ToolkitImage 不能转换为 java.awt.image.BufferedImage

please help me cant do this thing to work to me sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage

 if (shape.hasImage())
                    {
                        // If this shape is an image, extract image to file
                        String extension = ImageTypeToExtension(shape.getImageData().getImageType());
                        String imageFileName = MessageFormat.format("Image.ExportImages.{0} Out.{1}", imageIndex, extension);
                        String strBarCodeImageExtracted = "" + imageFileName;
                        shape.getImageData().save(strBarCodeImageExtracted);

                        // Recognize barcode from this image
                        BarCodeReader reader = new BarCodeReader ((BufferedImage) Toolkit.getDefaultToolkit().getImage(strBarCodeImageExtracted),BarCodeReadType.Code39Standard);
                        while (reader.read())
                        {
                            System.out.println("codetext: " + reader.getCodeText());
                        }
                        imageIndex++;
                    }

推荐答案

此答案在评论写完后被接受,因此必须假设评论是实际解决方案.评论是

This answer was accepted after the comment was written, so one has to assume that the comment was the actual solution. The comment was

... 将 Toolkit.getDefaultToolkit().getImage(...) 替换为 ImageIO.read(...) ...

原答案:

您可以尝试使用 ImageIO 直接读取图像,或者考虑将图像绘制到新分配的 BufferedImage 中,例如使用像

You may either try to read the image direcly with ImageIO, or consider painting the image into a newly allocated BufferedImage, e.g. with a method like

public static BufferedImage convertToBufferedImage(Image image)
{
    BufferedImage newImage = new BufferedImage(
        image.getWidth(null), image.getHeight(null),
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return newImage;
}

然后在你的情况下:

Image image = Toolkit.getDefaultToolkit().getImage(strBarCodeImageExtracted);
BufferedImage bufferedImage = convertToBufferedImage(image);
BarCodeReader reader = new BarCodeReader(bufferedImage,BarCodeReadType.Code39Standard);

这篇关于错误:sun.awt.image.ToolkitImage 无法转换为 java.awt.image.BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:53