Base64 To ImageIO

时间:2014-05-26 07:29:35

标签: java image jsp base64 javax.imageio

我正在尝试将base64字符串转换为imageIO并保存它。

在更大的背景下,我正在创建一个脚本,以便用户可以上传图像,裁剪图像并将其保存为个人资料图像。我从这个裁剪的图像中得到一个Base64字符串,并将其发送到servlet。 (是的,我正在使用Java Server Pages)

问题在于: 当我执行以下代码时,我在方法decodeToImage中的变量Image上得到一个空指针。

我尝试使用其他几个库来解码base64,但还没有结果。 我试图使用其他图像转换脚本但没有工作。

此外,在我看来这个代码应该可行。我错过了什么吗?

提前致谢!

欢迎所有反应!

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    if(request.getParameter("upload-CroppedImage") != null){


        BufferedImage newImage = decodeToImage(request.getParameter("croppedImage"));

        File outputfile = new File("F:\\Users\\Joery v2\\Pictures\\saved.jpg");
        ImageIO.write(newImage, "jpg", outputfile);
    }
}

public static BufferedImage decodeToImage(String imageString) {

    try {
        byte[] imgBytes = parseBase64Binary(imageString);
         BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgBytes));
         return image;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

*这是来自servlet的代码。

堆栈追踪:

Info:   GameZ_Website was successfully deployed in 2.076 milliseconds.
Warning:   StandardWrapperValve[CroppingImage]: Servlet.service() for servlet CroppingImage threw exception
java.lang.IllegalArgumentException: image == null!
    at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)

1 个答案:

答案 0 :(得分:2)

尝试此代码,以避免解码/编码周期,并查看您的图像是否符合预期:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    if (request.getParameter("upload-CroppedImage") != null) {
        String dataURI = request.getParameter("croppedImage");
        String data = dataURI.substring(dataURI.indexOf(',')); // TODO: Input validation
        byte[] imgBytes = parseBase64Binary(data);

        File outputfile = new File("F:\\Users\\Joery v2\\Pictures\\saved.jpg");
        writeBytesToFile(imgBytes, outputFile);
    }
}

private void writeBtesToFile(byte[] bytes, File file) {
    OutputStream out;

    try {
        out = new FileOutputStream(file);
        out.write(bytes);
    } 
    finally {
        out.close();
    }
}