保存頭像- 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"; } }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM