This is the 21st day of my participation in the August More Text Challenge

The front-end processing

The Data URI scheme is defined in RFC2397 to embed small Data directly into web pages without loading it from external files.

Base64 simply translates some 8-bit data into standard ASCII characters, and the content of the image file is written directly to the HTML file, saving an HTTP request. The downside is that browsers don’t cache this image.

The Data URI scheme supports the following types:

  • Data :, text data
  • Data :text/plain: indicates text data
  • Data: text/HTML, HTML code
  • data:text/html; Base64, Base64 encoded HTML code
  • Data: text/CSS, CSS code
  • data:text/css; Base64,base64 encoded CSS code
  • Data: text/javascript, javascript code
  • data:text/javascript; Base64, Base64 encoded Javascript code
  • data:image/gif; Base64,base64 encoded GIF image data
  • data:image/png; Base64,base64 encoded PNG image data
  • data:image/jpeg; Base64, Base64 encoded JPEG image data
  • data:image/x-icon; Base64, Base64 encoded icon picture data

In fact, you can also process PDF and other documents.

1. Display HTML tags

  • The IMG tag is used as an example
<img src="./images/test.jpg"/> <! -- Personal common way -->
Copy the code
  • Using base64 display form:
<img src="data:image/png; Base64,iVBORw0KGgoAAA Base64/>
Copy the code

2. Convert JavaScript images to Base64

  • I use a tool class to share, image conversion Base64
function image2Base64(img) {    // The image is base64 encoded
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0.0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

function getImgBase64(){        // Get base64 encoding
    var base64="";
    var img = new Image();
    img.src="img/test.jpg";
    img.onload=function(){
        base64 = image2Base64(img);
        alert(base64);
    }
}
getImgBase64();    // Use the function
Copy the code

Through the above code, in fact, we should be able to feel the need to Base64 encoding and transcoding images, the above is mainly used toDataURL for processing, in fact, there are other ways.

3. Base64 encoding and decoding with JS

Starting with IE10+, all browsers provide Base64 encoding and decoding methods natively, which can be used not only in browser environment but also in Service Worker environment. The method names are atob and bTOA. The syntax is as follows:

window.btoa('china is so nb') / / code
"Y2hpbmEgaXMgc28gbmI="
window.atob("Y2hpbmEgaXMgc28gbmI=") / / decoding
"china is so nb"
Copy the code

E8/IE9 polyfill. There are still many PC projects that need to be IE9 compatible, so we can introduce a Ployfill script or a JS file specifically for these browsers.

<! - [if IE]>
<script src="https://www.zhangxinxu.com/wordpress/2018/08/js-base64-atob-btoa-encode-decode/base64-polyfill.js"></script><! [endif]-->Copy the code
  • ** Code BTOA **
// base64 turns to a string
function getEncode64(str){
    // Encode the string
    var encode = encodeURI(str);
    // Convert the encoded string to base64
    var base64 = btoa(encode);
    return base64
}
Copy the code
  • ** Code ATOB **

// base64 turns to a string
function getDecode(str){
    // Transencode base64
    var decode = atob(base64);
    // Encode to string
    var str = decodeURI(decode);
    return str;
}
Copy the code
  • The sample code
let url = 'http://baidu.com'
// Switch to base64 encoding
let base64Url = this.getEncode64(url);
 
Parse parse is used to decode JSON. Normal object formats are not required
let data =JSON.parse(this.getDecode(resp.data));
console.log(data);
Copy the code

Base64. js is an open source base64.js file that is easy to use and imported by browsers.

  • Encoding callsencodeThe method is as follows:
Base64.encode('china is so nb'); / / code
"Y2hpbmEgaXMgc28gbmI="
Copy the code
  • Decode and calldecodeThe methods are as follows:
Base64.decode("Y2hpbmEgaXMgc28gbmI="); / / decoding
'china is so nb'
Copy the code

4. Chinese

Base64 encoding and decoding, THERE is no problem with my front-end operation to compile and decode Chinese, but because of the need for background, after encoding, it is transmitted to the background, and when the background returns the encoding format and then decodes, Chinese garbled characters will appear.

Reason: A search down, may be due to the normal encode method although the interface is utF-8, but in fact, the transfer of storage format or UTF-16, background return is UTF-8 format, with decode interface is actually utF-16 to UTF-8 will appear Chinese garble. That is to say, the above encoding and decoding, suitable for the page itself encoding decoding, not suitable for transmission.

Solve the problem of Chinese garble:

// Switch the string to base64
function getEncode64(str){   
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g.function toSolidBytes(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

function getDecode(str){
    return decodeURIComponent(atob(str).split(' ').map(function (c) {
        return The '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(' '));
}
Copy the code

5. Download and save pictures

I want to save this Base64 image locally by clicking the “Save button”.


// Save the button click event method
function saveImg(){
    var sampleImage = $("img") [0]; // Find the img tag for the image
    var canvas = convertImageToCanvas(sampleImage); // Create an artboard
    url = canvas.toDataURL("image/png"); // Generate the url for the download
    // Put the URL into our A tag and get the A tag object
    var triggerDownload = $("#saveImg").attr("href", url).attr("download"."ewm.png"); 
    triggerDownload[0].click(); // Click on the A TAB to download it.
}
 
/** * Generate canvas from image */
function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0.0);
    return canvas;
}


Copy the code

Another kind of reference code

// Here is the base64 encoding of the image. Here is just an example
 const imgUrl = 'data:image/png; base64,... '
 // If the browser supports the msSaveOrOpenBlob method (i.e. when using Internet Explorer), call this method to download the image
 if (window.navigator.msSaveOrOpenBlob) {
  var bstr = atob(imgUrl.split(', ') [1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
   u8arr[n] = bstr.charCodeAt(n)
  }
  var blob = new Blob([u8arr])
  window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '. ' + 'png')}else {
  // Use chrome and other newer browsers to handle this
  const a = document.createElement('a')
  a.href = imgUrl
  a.setAttribute('download'.'chart-download')
  a.click()
 }
Copy the code

Server-side processing

About the background processing, I will paste my code, do not want to write, you can use it

  • The Base6 conversion utility class,Java8 processing performance is betterimport java.util.Base64;
package com.hanpang.common;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Util {
    private static final String UTF8="UTF-8";
    private static Base64.Encoder encoder;
    // This is the safe encoding mode. Replace "+" "/" "-" with "_".
    private static Base64.Encoder urlEncoder;
    private static Base64.Decoder decoder;
    private static Base64.Decoder urlDecoder;
    static {
        encoder = Base64.getEncoder();
        urlEncoder = Base64.getUrlEncoder();
        decoder = Base64.getDecoder();
        urlDecoder = Base64.getUrlDecoder();
    }
    / / encode coding
    public static byte[] encode(byte[] bytes) {
        return encoder.encode(bytes);
    }
    public static String encode(String string) {
        byte[] encode = encode(string.getBytes());
        try {
            return new String(encode, UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String encode2String(byte[] bytes) {
        return encoder.encodeToString(bytes);
    }
    public static byte[] encode2Byte(String string) {
        return encode(string.getBytes());
    }
    public static byte[] urlEncode(byte[] bytes) {
        return urlEncoder.encode(bytes);
    }
    public static String urlEncode(String string) {
        byte[] encode = urlEncode(string.getBytes());
        try {
            return new String(encode, UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String urlEncode2String(byte[] bytes) {
        return urlEncoder.encodeToString(bytes);
    }
    public static byte[] urlEncode2Byte(String string) {
        return urlEncode(string.getBytes());
    }
    / / encode coding
    public static byte[] decode(byte[] bytes) {
        return decoder.decode(bytes);
    }
    public static byte[] decode2Byte(String string) {
        return decoder.decode(string.getBytes());
    }
    public static String decode2String(byte[] bytes) {
        try {
            return new String(decoder.decode(bytes),UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String decode(String string) {
        byte[] decode = decode(string.getBytes());
        try {
            return new String(decode, UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //urlDecode
    public static byte[] urlDecode(byte[] bytes) {
        return urlDecoder.decode(bytes);
    }
    public static byte[] urlDecode2Byte(String string) {
        return urlDecode(string.getBytes());
    }
    public static String urlDecode2String(byte[] bytes) {
        try {
            return new String(urlDecode(bytes),UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String urlDecode(String string) {
        byte[] decode = urlDecode(string.getBytes());
        try {
            return new String(decode, UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null; }}Copy the code
  • Interchange tool classes
package com.hanpang.common;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Arrays;

public final class Base64Convert {
    /** * Image is converted to Base64 string *@param imagePath
     * @return* /
    public static String imageToStr(String imagePath){
        File imageFile = new File(imagePath);
        if(! imageFile.exists()){throw new RuntimeException("Picture does not exist, please check after processing");
        }
        try {
            byte[] bytes = FileUtils.readFileToByteArray(imageFile);
            return Base64Util.encode2String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** * base64 string to image *@paramImageData image encoding *@paramImageFilePath is stored in the local path *@return* /
    public static void strToImage(String imageData,String imageFilePath){
        if(imageData==null||imageData.trim().length()==0) {throw new RuntimeException("There is a problem with the string data. Please restart it before converting.");
        }
        byte[] bytes = Base64Util.decode2Byte(imageData);
        try {
            IOUtils.copy(new ByteArrayInputStream(bytes),new FileOutputStream(imageFilePath));
        } catch(IOException e) { e.printStackTrace(); }}/** * large files are converted to Base64 strings, which should not be used in general@param filePath
     * @return* /
    public static String fileBigToStr(String filePath){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            byte[] b = new byte[3 * 1024 * 1024];// Since three regular characters can be converted to four Base64 encoded characters, a common multiple of 3 is used as the buffer size
            byte[] base64Buffer;
            int len;
            while((len=in.read(b))! = -1) {if(len! =b.length){// If the number of valid bytes is not 3 * 1024 * 1024, the file has been read to the end and is not enough to fill b
                    byte[] copy = Arrays.copyOf(b, len);// Intercepts a byte segment containing the number of valid bytes from b
                    base64Buffer = Base64Util.encode(copy);// Encode a valid byte segment
                }else{
                    base64Buffer = Base64Util.encode(b);
                }
                out.write(base64Buffer,0,base64Buffer.length);
                //FileUtils.writeByteArrayToFile(file, base64ByteBuf, true); // Write the converted data to a file. This method automatically creates the file
                out.flush();
            }
            in.close();;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("File does not exist, please check after processing");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("There was a problem reading the file");
        }
        returnout.toString(); }}Copy the code