base64转图片出现的问题及解决方案
代码:String r = request.getParameter("r")+"";//前台传过来的base64字符串String filename = "";String filepath = "";String path1 = request.getSession().getServletContext().ge
·
代码:
String r = request.getParameter("r")+"";//前台传过来的base64字符串
String filename = "";
String filepath = "";
String path1 = request.getSession().getServletContext().getRealPath("/img/uploadPicture");
filepath = path1 + "/" + (new Date().getTime())+""+filename;//存储路径
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
try{
byte[] b = decoder.decodeBuffer(r);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
java.io.OutputStream out = new java.io.FileOutputStream(filepath);
out.write(b);
out.flush();
out.close();
}catch (IOException e){
e.printStackTrace();
}
问题描述:代码执行的过程中,程序不报错,但是转成的图片大小是0K,打不开。
问题原因:base64字符串的开头是 "data:image/jpeg;base64," ,不属于图片内容的字符串,因该去掉。
解决方案:将上述原因中的代码去掉即可。
最终代码:
String r = request.getParameter("r")+"";//前台传过来的base64字符串
String r3 = r.substring(r.indexOf(",")+1);//去掉base64字符串的开头部分
String filename = "";
String filepath = "";
String path1 = request.getSession().getServletContext().getRealPath("/img/uploadPicture");
filepath = path1 + "/" + (new Date().getTime())+""+filename;//存储路径
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
try{
byte[] b = decoder.decodeBuffer(r3);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
java.io.OutputStream out = new java.io.FileOutputStream(filepath);
out.write(b);
out.flush();
out.close();
}catch (IOException e){
e.printStackTrace();
}
更多推荐


所有评论(0)