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 ; }

 

转载于:https://www.cnblogs.com/zhuyupingit/p/9454354.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值