What is Base64:
Base64 is one of the most common encoding methods for transmitting 8Bit bytecode on the network. Base64 is a method to represent binary data based on 64 printable characters.
Advantages and disadvantages of converting images to Base64 format
advantages
- Base64 image is text format, which occupies a small memory, and the size ratio after conversion is about 1/3, which reduces the consumption of resource server.
- When base64 images are used in web pages, there is no need to request the server to call image resources, which reduces the number of server visits.
- Base64 encoded string, more suitable for different platforms, different languages transmission;
- The algorithm is encoding, not compression, and will only increase the number of bytes after encoding, but the algorithm is simple, almost does not affect the efficiency, the algorithm is reversible, decoding is very convenient, not used for private information communication;
- Decoding is convenient, but after all the coding, the naked eye can not directly see the original content;
disadvantages
- There are a lot of text content in Base64 format, which is stored in the database and increases the pressure of the database server.
- Although the web page load image does not need to visit the server, but because of the base64 format of content, so the speed of loading web pages will be slow, which may affect the user experience.
- Base64 cannot be cached. Only files containing Base64 can be cached, such as JS or CSS, which is much worse than direct caching of images. Besides, HTML changes are frequent, so it is equivalent to not getting the benefit of caching.
How does javascript convert image absolute addresses to Base64
function getBase64Image(url) {
const img = new Image()
// This property can solve the cross-domain problem, which is explained below
img.setAttribute("crossOrigin".'anonymous');
// If you want to be compatible with ios, the two sequences must not be changed. CrossOrigin is set first and SRC is set later
img.src = url;
return new Promise((resolve, reject) = > {
img.onload = () = > {
Canvas base configuration
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0.0, canvas.width, canvas.height);
resolve({
success: true.The canvas.toDataURL method converts the absolute path of the image to base64 encoding
base64: canvas.toDataURL()
})
}
img.onerror = () = > {
reject({ success: false})}})}/ / call
getBase64Image('https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eav HiaiceqxibJxCfHe/46')
.then(res= >{
console.log(res) // {success : true, base64 :'data:image/png; Base64, iVBORw0KGgoAAAANSUhEUgAAAC4A... etGgbgs19tVBD5K/+l/8/4jpK+RseVK4AAAAASUVORK5CYII='}
})
Copy the code
CrossOrigin properties
If you have a cross-source image, you can copy it to the canvas, but this “smudges” the canvas and prevents you from reading it (so you can’t “steal” the image, for example from an internal website without accessing the site itself). However, with CORS, the server storing the image can tell the browser to allow cross-source access, so you can access the image data through the canvas. This attribute has two optional values: anonymous: If you use this value, the Origin attribute will be added to the header in the request, but the request will not include cookies or other authentication information. Use-credentials: These carry cookies and other authentication information with them in cross-domain requests. If you just write blank crossOrigin= “, it will have the same effect as anonymous
At the end
When using Webpack packaging, our project can selectively convert pictures to Base64 according to the actual situation. Webpack needs urL-loader and file-loader. The former relies on the latter, so it needs to be installed, but it does not need special configuration, so it can be written like this
module : {
rules: [{JPG, PNG, GIF, jpeg
test: /\.(jpg|png|gif|jpeg)$/.// url-loader is required
loader: 'url-loader'.options: {
If the value is below 50K, the base64 will be changed to base64 by default
limit: 50 * 1024.If base64 is not converted, the image name will be packaged as a unique hash value, but the hash value is too long, so you can set the length of the file name, where 10 is the first 10 bits of the hash value, ext means to keep the original suffix
name: '[hash:10].[ext]'.//url-loader defaults to es6 and uses commonJs instead of es6
esModule : false,}},]}Copy the code