java将base64转成image

来源:互联网 发布:郑州做seo的工资 编辑:程序博客网 时间:2024/05/17 02:16

前后端分离后,前端从h5页面传递的图片是base64格式的,需要后台将base64转成图片,然后上传到图片服务器上。在base64转成image需要引入以下jar:sun.misc.BASE64Decoder.jar 这里写图片描述
java代码:

package com.wellness.platfront.common.util;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import javax.annotation.Resource;import org.springframework.stereotype.Component;import com.wellness.platfront.common.server.ApiUploadService;import Decoder.BASE64Decoder;/** * 将base64转换成image * @author Administrator * */public class ConvertBase64ToImage {     ApiUploadService apiUploadService =new ApiUploadService();     /**时间戳格式*/    private static  DateFormat formate =new SimpleDateFormat("yyyyMMdd");    //base64字符串转化成图片      public static File GenerateImage(String imgStr)      {   //对字节数组字符串进行Base64解码并生成图片          if (imgStr == null) //图像数据为空              return null;          BASE64Decoder decoder = new BASE64Decoder();          String uuid = CommonUtil.generateUUID();        String uuidpath =uuid.substring(0, 4);        //生成文件名        try           {              //Base64解码               byte[] b = decoder.decodeBuffer(imgStr);              for(int i=0;i<b.length;++i)              {                  if(b[i]<0)                  {//调整异常数据                      b[i]+=256;                  }              }              //生成jpeg图片              String imgFilePath =Struts2Utils.getRealPath()+"/"+uuid+".jpg";//新生成的图片              OutputStream out = new FileOutputStream(imgFilePath);                  out.write(b);              out.flush();              out.close();              File file = new File(imgFilePath);            return file;          }           catch (Exception e)           {              return null;          }      }  }

调用代码:(调用时需要前端把base64码的标志头去掉)

File files = ConvertBase64ToImage.GenerateImage(memberImg);//删除文件files.delete();

这里写图片描述

原创粉丝点击