How to display the base64 format of the front-end img image (and download it locally)

Such as the title: I have been working on a project recently and found that some pictures on the page are dynamically obtained, that is, the storage address of the picture returned to us by the background, usually placed in a certain location on the server, we can just get it and render it directly, (premise There is no cross-domain problem),

However, due to the particularity of the project, the image rendered by Python in the background is in svg format, and it is a vector image. It is not easy to convert it into a png image, and the address cannot be directly stored, so I thought of using base64. .

For example:

 <div class="scatter" id="scatter" > 
      <img :src="inputImg" alt="" :style="{width:widthImg,height:heightImg}">
 </div>


//下面 直接使用vue 语法

// 接口获取到的 字段直接赋值即可

  this.inputImg = 'data:image/svg+xml;base64,' + res.data.body.data

The return format of this background data is as follows:

The background data above returns a vector image in svg format. In order to be clearer and not distorted, this method is adopted, so we write its suffix accordingly. Because it is in xml format, we write 'data:image/svg+xml; base64,'

Since there are pictures like svg, there are also pictures in png, jpg, jpeg and other formats. We only need to determine the logic and method used in the background to return the corresponding format. The jpeg format: this.imgUrl='data:image/jpeg; base64, '+res.data.data,

Other pictures should be similar, and the cross-domain problem can be solved by itself.

So how to download the displayed pictures to the local?

Solution: Image data is embedded in HTML or Js in the form of a Base64-encoded string. If you want to save this image locally, you need to convert the Base64-encoded string into binary data and store it as a document. You can use the a tag directly, or you can use buttons or other tags. Below I use the el-button button of Ele.me ui

code:

<el-button type="primary" size="mini"  @click="updown">下载结果</el-button>


//对应的方法
updown(){
    var objimg='' 
   //这里objimg 表示图片显示的路径  一般都是data:image/jpeg;base64,iVBORw0KGgoAAAANS
   const byteCharacters = atob(objimg.split(',')[1])
   const byteNumbers = new Array(byteCharacters.length)
   for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
   }
   const byteArray = new Uint8Array(byteNumbers)
    //区分是什么类型的 svg 或者是png 格式 切记不同类型后缀不同。使用错误可能会下载图片打不开
    var blobs=''
    if(this.active=='first' || this.active=='second' ||                
      this.active=='third'){
      blobs = 'image/svg+xml'
     }
     if(this.active=='four'){
          blobs = 'image/png'
     } 
     this.downLong=false
       let url = window.URL.createObjectURL(
              new Blob([byteArray], { type: blobs })
       );
       let link = document.createElement("a"); //创建a标签
       link.style.display = "none"; //将a标签隐藏
       link.href = url; //给a标签添加下载链接
       link.setAttribute("download", '运行结果图片' ); 
       document.body.appendChild(link);
       link.click(); //执行a标签
}

What to pay attention to is: first get the image path, and parse it into the corresponding type. We only parse the string after "base64," so split it first, and then generate different download suffixes according to different types. That's it.

Of course, you can directly use the a tag to represent it. Here is an example in png format. For other formats, refer to the above method, which is basically the same.

<a :href="downloadUrl" download="image.png">下载图片</a>

//方法
downloadUrl() {
      // 将 Base64 编码的字符串转换为二进制数据
      var objimg='' 
     //这里objimg 表示图片显示的路径  一般都是  data:image/jpeg;base64,iVBORw0KGgoAAAANS
      const byteCharacters = atob(objimg.split(',')[1])
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)

      // 创建 Blob 对象并将其转换为 URL
      const blob = new Blob([byteArray], { type: 'image/png' })
      return URL.createObjectURL(blob)
    }

Knowledge point: atob is a method for parsing base64 strings in the js function. It also has a brother btoa that is edited into base64 format.

        charCodeAt() is a string method used to retrieve the Unicode value of a character at a specific position in a string.

        Uint8Array is an array of 8-bit unsigned integers with a length of 1 byte.

Guess you like

Origin blog.csdn.net/qq_42174597/article/details/130490859