java上传不同类型图片,保存数据库(Base64位图转网络图片)
直接上代码好不好
方法名:
GenerateImage
传参:
base64Img:上传的base64码
realPath:生成的图片路径
imgTypes :图片类型
String imgBase64 = request.getParameter("userImgbase64");
// 获取当前服务器路径
String realPath = request.getServletContext().getRealPath("")+"\\img";
System.out.println(realPath ); // http://192.168.191.1:8080/MyWeb/img
String[] imgType = imgBase64.split(",");
// 获取图片类型(如果没有类型,貌似会报错)
String imgTypes = imgType[0].toString().substring(11, imgType[0].toString().length()-7);
String userImgbase64 = GenerateImage(imgBase64,realPath,imgTypes);
System.out.println(realPath ); // http://192.168.191.1:8080/MyWeb/img/1532493648717.png
//对字节数组字符串进行Base64解码并生成图片 public static String GenerateImage(String base64Img,String realPath,String imgTypes ){ String ret_fileName = null; // 临时文件路径 File file_normer = new File(realPath+"/"); if (!file_normer.exists()) { file_normer.mkdirs(); } if (base64Img == null) // 图像数据为空 return "图像数据为空"; base64Img = base64Img.replaceAll("data:image/"+imgTypes+";base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(base64Img); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } // 生成jpeg图片 ret_fileName = System.currentTimeMillis()+"."+imgTypes+""; File file = new File(realPath + "/" + ret_fileName ); OutputStream out = new FileOutputStream(file); out.write(b); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return ret_fileName ; }