使用Java和Base64解码进行解谜并生成图片
工具类ImgUtil:
-import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import com.mb.service.impl.GSAPIServiceImpl;
import sun.misc.BASE64Decoder;
@SuppressWarnings("restriction")
public class ImgUtil {
public static String pa;
public static Object FromBase64ToImage(String strImage, String fileName, int maxSize,HttpServletRequest req) throws IOException{
//String webpath=req.getContextPath();
Properties p = new Properties();
p.load(ImgUtil.class.getClassLoader().getResourceAsStream("configurationfile.properties"));
String webpath = req.getSession().getServletContext().getRealPath("/");
String YM=new SimpleDateFormat("yyyyMM").format(new Date());
String path= "\\files\\SQ\\" + YM + "\\";
String urlPath = p.getProperty("imgUrl")+"/files/SQ/" + YM + "/";
String imagePath = webpath + path;
pa=urlPath+fileName;
File file=new File(imagePath);
if(!file .exists() && !file .isDirectory()){
file .mkdirs();
}
if(strImage.indexOf(',')>0){
String[] strBase64 = strImage.split(",");
if(strBase64 != null && strImage.length() >= 2){
strImage = strBase64[1];
}
}
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码
byte[] bytes = decoder.decodeBuffer(strImage);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imagePath+fileName);
out.write(bytes);
out.flush();
out.close();
return imagePath;
}
}
测试:
Object fromBase64ToImage = ImgUtil.FromBase64ToImage(imgdata, java.util.UUID.randomUUID() + “.jpg”, 300,req);
//ChangeHeadImage方法修改头像
int changeHeadImage = userService.ChangeHeadImage(userid, ImgUtil.pa);