[英]Base64 To ImageIO
I'm trying to convert a base64 string to an imageIO
and saving it. 我正在尝试将base64字符串转换为
imageIO
并保存。
In a bigger context, I'm creating a script so users can upload an image, crop it and save it as their profile image. 在更大的上下文中,我正在创建一个脚本,以便用户可以上传图像,裁剪图像并将其保存为个人资料图像。 I get a
Base64
String from this cropped image, and sent it to the servlet. 我从此裁剪的图像中获取了
Base64
字符串,并将其发送到servlet。 (Yes, I'm using Java Server Pages) (是的,我正在使用Java Server Pages)
Here is the problem: When i execute the following code, i get a null pointer on my variable Image in the method decodeToImage
. 这是问题所在:当我执行以下代码时,我在我的变量Image中获得了一个null指针,该方法的
decodeToImage
。
I tried to use several other libraries to decode the base64 but with no results yet. 我尝试使用其他几个库对base64进行解码,但没有结果。 I tried to use other image convert scripts but none worked.
我尝试使用其他图像转换脚本,但是没有一个起作用。
Also this code seems to me that is should work. 在我看来,这段代码也应该起作用。 Am i missing something?
我想念什么吗?
Thanks in advance! 提前致谢!
All reactions are welcome! 欢迎所有反应!
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;
}
*This is code from the servlet. *这是来自servlet的代码。
Stack Trace: 堆栈跟踪:
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)
Try this code, to avoid the decode/encode cycle, and see if your image looks as expected: 尝试使用以下代码,以避免解码/编码周期,并查看图像是否符合预期:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.