代码之家  ›  专栏  ›  技术社区  ›  Abzelhan

Java Thumbnailator库:发生IIOException:读取PNG元数据时出错

  •  1
  • Abzelhan  · 技术社区  · 7 年前

    我使用 this 用于创建图像缩略图的开放源代码库。我的任务是将文件转换为Base64字符串,然后将此字符串作为请求参数发送给REST服务。我使用以下函数在客户端将文件转换为Base64字符串:

    public String convertToBase64(File file) throws IOException {
        byte[] bytes = new byte[(int)file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(bytes);
        return new String(Base64.encodeBase64(bytes), "UTF-8");
    }
    

    然后我检索这个encodedString并将这个字符串作为请求参数发送给REST服务。

    在REST服务中,我使用以下函数解码此字符串:

        public static void uploadBase64Image(String file, String filename) throws Exception {
        filename = filename.replaceAll(" ", "_");
        byte[] data = DatatypeConverter.parseBase64Binary
                (file.replaceFirst("data:image/jpg;base64,", "")
                        .replaceFirst("data:image/jpeg;base64,", "")
                        .replaceFirst("data:image/png;base64,", ""));
        File tempFile = File.createTempFile("base64", filename);
        FileUtils.writeByteArrayToFile(tempFile, data);
    
        FileEntity fe = FileEntity.processAndCompressFile(tempFile, "pic");
        fe.save();
        renderJSON(fe.getJson());
    }
    

    这个 DatatypeConverter 位于下 package javax.xml.bind;

    问题是当我尝试制作此tempFile的缩略图时出现的。我尝试制作缩略图的代码部分:

    private static String compressFileAndGetFilenameWithExt(File originalFile, int height, String filename, String fileExt) throws Exception {
        StringBuilder newFileName = new StringBuilder(filename)
                        .append("_")
                        .append(height)
                        .append(fileExt);
        File compressedFile = new File(filesLocation + newFileName.toString());
        Thumbnails.Builder<File> builder = Thumbnails.of(originalFile);
        builder = builder.height(height);
        builder.toFile(compressedFile);
        return newFileName.toString();
    }
    

    我明白了 发生IIOException:读取PNG元数据时出错 在这一行代码中: builder.toFile(compressedFile);

    有人能解释一下并帮我解决这个问题吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Abzelhan    6 年前

    我找到了袋子的解决方案。这是因为我没有配置头来获取文件