The basic concept
The vector diagram
Vector graph is based on geometric characteristics to draw graphics, vector can be a point or a line, vector graph can only be generated by software, the file occupies less internal space, because this type of image file contains independent separated images, can be freely unlimited recombination.
Advantages: small file capacity, zoom in, zoom out or rotate the image will not be distorted.
Disadvantages: not easy to make images with too many color changes.
Front-end vector format: SVG
The bitmap
Bitmaps are made up of individual points called pixels (picture elements). These points can be arranged and dyed differently to form a pattern. When you zoom in on the bitmap, you can see the countless individual squares that make up the entire image. Enlarging the size of a bitmap has the effect of increasing the size of a single pixel, making lines and shapes appear uneven. However, when viewed from a distance, the color and shape of the bitmap image appear to be continuous.
Advantages: as long as there are enough pixels of different colors, you can make a colorful image, realistic performance of the scene of nature.
Disadvantages: Easy distortion of zoom and rotation, and large file capacity.
Front end use bitmap formats: JPG/JPEG, PNG, APNG, webp, CIF, ICO
Lossy compression
Is the use of statistical redundancy data compression, can completely restore the original data without causing any distortion.
Lossless compression
It takes advantage of the insensitivity of human to some frequency components in the image or sound wave, allowing the loss of certain information in the compression process
Image format
JPEG/JPG
JPEG (Joint Photographic Experts Group) is the product of the JPEG standard, which is formulated by the International Organization for Standardization (ISO). It is a compression standard for continuous tone still images. The JPEG format is the most common image file format, with the suffix.jpg or.jpeg.
Compression mode
There are many compression modes for JPEG. Here are some common compression encoding modes:
Standard compression mode
This type can only display the image from top to bottom when downloading the web page, until all the image information is downloaded, you can see the full picture of the image.
Incremental model
This type gives a rough look of the image before slowly rendering the full content when downloading from a web page, and a document saved in progressive JPG is smaller than a standard JPG document, so you can use this format more often if you want to use images on a web page.
How do you tell if an image is progressive? The scaffolding tool is-progressive-cli is recommended
The installation
npm install --global is-progressive-cli
Copy the code
The basic use
is-progressive test.jpg
Copy the code
How do you turn an image into a progressive image? Can use a lot of third-party tools for processing, such as: imagemin, libjpeg, imageMagick, etc
For example, in GLUP, use gulp-Imagemin
import gulp from 'gulp';
import imagemin from 'gulp-imagemin';
export default () => (
gulp.src('src/images/*')
.pipe(imagemin({
progressive: true
))
.pipe(gulp.dest('dist/images'))
);
Copy the code
In Webpack, use the Imagemin-webpack-plugin
import ImageminPlugin from 'imagemin-webpack-plugin'
import imageminMozjpeg from 'imagemin-mozjpeg'
module.exports = {
plugins: [
new ImageminPlugin({
plugins: [
imageminMozjpeg({
quality: 100,
progressive: true
})
]
})
]
}
Copy the code
Other JPEG encoding modes
MOZJPEG encoding mode.
Improved JPEG compression efficiency while achieving higher visual quality and smaller file sizes.
Features:
- It has progressive coding. It can be applied to any JPEG file to reduce file size losslessly.
- Grid quantization. It maximizes the quality/file size ratio when converting other formats to JPEG.
- With new quantization table presets, adjusted for high resolution monitors, for example.
- Fully compatible with all Web browsers.
- Seamlessly integrates into any application that uses the industry-standard Libjpeg API. You don’t need to write any mozjpeg-specific integration code.
Imagemin – mozjpeg, for example
const imagemin = require('imagemin'); const imageminMozjpeg = require('imagemin-mozjpeg'); (async () => { await imagemin(['images/*.jpg'], 'build/images', { use: [ imageminMozjpeg() ] }); console.log('Images optimized'); }) ();Copy the code
Guetzli encoding mode
Designed to achieve excellent compression density with high visual quality. Guetzli produces images that are typically 20-30% smaller than the equivalent quality produced by libjpeg. Guetzli only generates sequential (non-progressive) JPeGs because they provide faster decompression.
Imagemin – guetzli, for example
const imagemin = require('imagemin');
const imageminGuetzli = require('imagemin-guetzli');
imagemin(['images/*.{png,jpg}'], 'build/images', {
use: [
imageminGuetzli({quality: 95})
]
}).then(() => {
console.log('Images optimized');
});
Copy the code
Matters needing attention
JPEG/JPG, it supports extremely high compression rates, so JPEG images download much faster. It easily handles 16.8m colors and can reproduce full-color images well. The image format allows the freedom to choose between the minimum file size (the lowest image quality) and the maximum file size (the highest image quality) during the image compression process. The file size of the format is relatively small, and the download speed is fast, which is good for transmission when bandwidth is not “rich”. However, the quality of the image may be lost during compression, so it is not suitable to use this format to display high-resolution images.
GIF
The full name for GIF is Graphics Interchange Format. GIF works best with less colorful images, such as cartoons, corporate logos, etc. The later PNG format is better, so GIFs are generally used to display animations
Convert a single GIF frame to a PNG
Take Node-Imagemagick as an example:
let im = require('node-imagemagick'); // identify(['-format', '%m', 'kittens. JPG '], function(err, output){if (err) throw err; console.log('dimension: '+output); // dimension: 3904x2622 }); // Convert im.convert(['kittens. GIF ', 'kittens. PNG '], function(err, stdout){if (err) throw err; console.log('stdout:', stdout); });Copy the code
GIF animation optimization
In some cases, giFs may contain static frames, which usually don’t differ much. Tools can be used to remove duplicate image information. Take Gifsicle as an example. There are many other compression tools such as compresse-images.
import {execFile} from 'node:child_process'; import gifsicle from 'gifsicle'; execFile(gifsicle, ['-o', 'output.gif', 'input.gif'], error => { console.log('Image minified! '); });Copy the code
Use video instead of animation
The disadvantages of animating with GIFs are many:
(1) no sound (2) time received limit (3) image quality problems (4) GIF decoding CPU time is serious
So if you don’t have to, cut back on giFs.
PNG
PNG is a bitmap format using lossless compression algorithms. It is designed to try to replace GIF and TIFF file formats while adding some features that GIF file formats do not have.
The characteristics of
Smaller size, more optimized network transfer, support transparent effect (this feature is GIF and JPEG do not) ****
Png8 and png24
Png8: Alias for 256-color PNG, pNG-8 uses lossless compression and is a bitmap format based on 8-bit indexed colors. Png-8 has better transparency support than GIF and is smaller for the same quality. But animations are not supported.
Png24: Alias for panchromatic PNG. Use full-color PNG instead of JPEG, but larger in size.
Compared with the GIF
1. Under normal circumstances, the compression rate will be slightly improved after the static GIF image is lossless converted to PNG.
PNG can provide support for greater color depth.
3. When converting PNG images with more than 8 bit color depth to GIF, the image quality will be degraded due to color separation (color count reduction).
4, GIF native support dynamic images, PNG can only be achieved through non-standard, on the basis of PNG has developed APNG and MNG formats to support animation, but the popularity is not high.
Compared with JPEG
1, because JPEG uses a specific lossy encoding method for photographic images, this encoding is suitable for low contrast, image color transition smooth, noisy, and irregular structure. If PNG is used instead of JPEG in this case, the file size increases significantly with limited improvement in image quality.
2. If you save text, lines, or similar images with sharp edges and large areas of the same color, PNG compression is much better than JPEG, and you don’t lose the high-contrast areas that JPEG does.
3. If the image has both sharp edges and the characteristics of a photo image, there is a trade-off between the two formats. JPEG does not support transparency.
Optimization of PNG
Imagemin – pngquant, for example
const imagemin = require('imagemin'); const imageminPngquant = require('imagemin-pngquant'); (async () => { await imagemin(['images/*.png'], { destination: 'build/images', plugins: [ imageminPngquant() ] }); console.log('Images optimized'); }) ();Copy the code
webp
WebP (pronounced: Weppy) is an image file format that provides both lossy and lossless compression (reversible compression). Originally released in 2010, the goal was to reduce file sizes but achieve the same image quality as JPEG, with the hope of reducing the time it takes to send images across the web. According to Google, this format reduces image size by 40 percent compared to JPEG
Compatibility:
Therefore, WebP compatibility is not good.
You are advised to obtain the compatibility solution using the following files:
Github.com/rico-c/RICO…
use
Use in Webpack:
Installation:
npm install webp-loader --save-dev
Copy the code
Basic use:
loaders: [
{
test: /.(jpe?g|png)$/i,
loaders: [
'file-loader',
'webp-loader'
]
}
]
Copy the code
SVG
SVG is an XML-defined language for describing two-dimensional vectors and vector/raster graphics. It offers advantages that the popular PNG and JPEG formats on the Web don’t: you can zoom in on graphics at will, but never at the expense of image quality. Preserve editable and searchable state in SVG images; On average, SVG files are much smaller than JPEG and PNG files and therefore download quickly.
Optimization suggestions:
(1) Reduce notes, hide layers, meta information and other redundant information.
(2) Do not insert bitmaps in SVG
(3) Use more SVG predefined shapes and less curves.
Svgo is recommended for optimization:
The installation
yarn add svgo-loader -D
Copy the code
Basic use:
module.exports = { ... , module: { rules: [ { test: /.svg$/, use: [ { loader: 'file-loader' }, { loader: 'svgo-loader', } ] } ] } }Copy the code
Base64
Base64 is not a picture format, but a way of encoding. According to base64 encoding principle, after encoding, the size of the image will normally expand by three quarters, so try to avoid base64
BMP format
BMP, short for Bitmap, is a standard image file format in The Windows operating system. This format contains rich image information and is hardly compressed. However, it has the inherent disadvantage of occupying too much disk space. Therefore, BMP is popular on a single machine.
Standing on the shoulders of giants
www.zhangxinxu.com/wordpress/2…
Github.com/rico-c/RICO…
There’s also something from Wikipedia