随笔 - 33  文章 - 0  评论 - 5  阅读 - 15万

保存头像- vue项目-base64字符串转图片

复制代码


<
img :onerror="errpic" class="customerHead" :src="param.customerHead" alt="">


data() {

  return {

    param:{ 

      id:"",
      customerHead: "",

    }

  }

}

复制代码
复制代码
let _this = this
let files = e.target.files[0]
if (files.size/(1024*1024) > 2) {
this.open('上传的图片不可大于2M!')
return false;
}
var reader = new FileReader();
reader.onload = function (e) {
var base64 = e.target.result;
_this.param.customerHead = base64
//console.log(base64)
}
if(files) {
reader.readAsDataURL(files);
}
复制代码

 

如果修改头像,向后台传base64字符串,否则会传原图片路径,后台判断是否是base64字符串.

 

如果是base64字符串,则对base64字符串进行处理,在后台服务器生成图片.此处需要对base64字符串进行处理,如图所示,删除蓝框部分,留逗号之后的内容.

若为图片路径,则不需要进行处理,直接返回图片路径即可.

 

复制代码
@Value("${upload.image.path}")
private String filePath;


//
base64字符串转化成图片 headerImgPath:http://+ip+:端口号 public String generateImage(String imgStr,String headerImgPath,String cusID) { //对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) //图像数据为空 return "../picclife/static/custom.png"; BASE64Decoder decoder = new BASE64Decoder(); try { //判断是base64字符串还是图片路径 if(imgStr.substring(0,5).equals("data:")){ //Base64解码 byte[] b = decoder.decodeBuffer(imgStr.substring(imgStr.indexOf(",") + 1)); for(int i=0;i<b.length;++i) { if(b[i]<0) {//调整异常数据 b[i]+=256; } } //生成图片 String imgFilePath = filePath+"/headerImg/"+cusID+".jpg";//新生成的图片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return headerImgPath+"headerImg/"+cusID+".jpg"; }else{ return imgStr; } } catch (Exception e) { return "../picclife/static/custom.png"; } }
复制代码

 

 

 

posted on   风景1573  阅读(5306)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示