曲殇~ 2023-06-17 15:12 采纳率: 50%
浏览 40

Toolkit.getDefaultToolkit().getImage()特殊格式图片加载失败

问题描述:excel导出图片使用ImageIO.read()加载部分图片会蒙上一层红色(应该是png格式手动
改为jpg的图片),所以换成了Toolkit.getDefaultToolkit().getImage()方法,但会导致特殊格式如webp图片无法加载,请问如何解决?

借鉴自:
https://zhidao.baidu.com/question/410085233.html

//写入图片
    private static void writeImg(Workbook workbook, Sheet sheet, Row currentRow, String imgPath, int currentColumnIndex, XSSFDrawing drawing) {
        try {
            logger.info("========Excel写入图片 ,开始。========");
            URL url = new URL(imgPath);
//            BufferedImage image = ImageIO.read(url);
            Image img = Toolkit.getDefaultToolkit().getImage(url);
            BufferedImage image = toBufferedImage(img);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            ImageIO.write(image, imgPath.substring(imgPath.lastIndexOf(".") + 1), byteArrayOut);

            //判断图片后缀
            int addPicture;
            String hz = imgPath.substring(imgPath.lastIndexOf(".") + 1);
            if("jpg".equals(hz)){
                addPicture = workbook.addPicture(byteArrayOut.toByteArray(), workbook.PICTURE_TYPE_JPEG);
            } else {
                addPicture = workbook.addPicture(byteArrayOut.toByteArray(), workbook.PICTURE_TYPE_PNG);
            }
//            ClientAnchor anchor = drawing.createAnchor( 50, 50, 50, 50, currentColumnIndex, currentRow.getRowNum(), currentColumnIndex + 1, currentRow.getRowNum() + 1);
            //图片位置
            XSSFClientAnchor anchor = new XSSFClientAnchor(100, 100, 100, 100, currentColumnIndex, currentRow.getRowNum(), currentColumnIndex + 1,currentRow.getRowNum() + 1);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
            drawing.createPicture(anchor, addPicture);
            logger.info("========Excel写入图片 ,结束。========");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            //此处会抛异常,但代码功能正常
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

图片红色详图:

img

  • 写回答

1条回答 默认 最新

  • IT论之程序员 2023-06-17 18:08
    关注

    这个问题是由于ImageIO只支持常见的图片格式,对于一些特殊的格式如webp图片无法加载导致的。
    解决方法有两种:

    1. 之前提到的使用Toolkit.getDefaultToolkit().getImage()方法来加载图片,这个方法的兼容性更好,可以加载更多格式的图片,但是对于一些特殊格式的图片加载速度会比较慢。
    2. 可以使用第三方图片库如Apache Batik来加载这些特殊格式的图片。Batik是一个SVG渲染工具包,它不仅可以渲染SVG图片,也支持加载PNG、JPG、GIF等常见格式和WEBP等特殊格式的图片。
      使用Batik的示例代码如下:
      java
      // 加载图片
      URL url = new URL(imgPath);
      TranscoderInput input = new TranscoderInput(url.openStream());
      PNGTranscoder transcoder = new PNGTranscoder();
      TranscoderOutput output = new TranscoderOutput(new ByteArrayOutputStream());
      transcoder.transcode(input, output);
      BufferedImage image = output.getBufferedImage();
      这样就可以成功加载webp等特殊格式的图片了。
      你可以选择上述两种方法中的一种来解决无法加载特殊图片格式的问题。
    评论

报告相同问题?

问题事件

  • 修改了问题 7月18日
  • 修改了问题 6月17日
  • 修改了问题 6月17日
  • 修改了问题 6月17日
  • 展开全部

悬赏问题

  • ¥15 在国外文献网站里点击view pdf 加载异常缓慢甚至加载不出来。
  • ¥50 python批量提取发票的信息
  • ¥15 mysql安装,初始化数据库失败
  • ¥15 虚幻五引擎内容如何上传至网盘?
  • ¥15 使用mmpose库时出现了问题
  • ¥15 IRI2016模型matlab运行报错
  • ¥50 bat怎么设置电脑后台自动点击网页指定词运行脚本,输入指定网页链接,指定点击词,指定间隔时间,指定网页出现的词,指定网页出现词出现后后点击锁定,放在后台运行不影响前台鼠标工作
  • ¥20 20CrMnMo的高温变形抗力
  • ¥15 RTX3.6 5565驱动中断报错
  • ¥50 带防重放token(Antireplay-Token)的网站怎么用Python发送请求