Home >Web Front-end >JS Tutorial >How to compress images using Node.js? Method introduction
Using Node.jsHow to compress images? The following article will introduce to you how to use Node.js to achieve image compression. Let’s take a look!
#. At that time, there was still one missing function: image compression, which was finally solved this time. At the same time, a legacy bug was also solved (the editor would get stuck if there were spaces in the link). Now it can be regarded as a fully functional plug-in. , interested friends can search for the plug-in
upload-to-qiniu in Vscode to install it.
[Recommended learning: "
nodejs tutorial"]
Effect preview:
2. Node compresses images
At first, I planned to use the
TinyPNG
imagemin instead. There is a pitfall here: because
imagemin cannot directly compress images, but needs to rely on
imagemin-jpegtran and
imagemin-pngquant
imagemin-pngquant
. One reason I found is that this library is based on some underlying languages, so it cannot be installed directly. You need to install another dependency on the computerlibpng .
Install libpng
Directly post the address for installing brew:zhuanlan.zhihu.com/p/90508170, just say it to him Basically, you can install brew by typing the command. Finally, we execute
brew install libpng. After
libpngis installed successfully, we can install imagemin-pngquant
in the project.buffer
object and returns a// 获取buffer export const getBufferFromFile = (filePath: string): Promise<Buffer> => { return new Promise((resolve, reject) => { fs.readFile(filePath, function (err: any, res: any) { if (!err) { resolve(res) } }) }) } // 压缩图片,传入图片文件路径,通过getBufferFromFile方法转为buffer 后进行压缩 const imageGzip = async (loaclFile: string): Promise<any> => { const bufferFile = await getBufferFromFile(loaclFile) let res try { res = await imagemin.buffer(bufferFile, { plugins: [ imageminJpegtran(), imageminPngquant({ quality: [0.6, 0.8], }), ], }) } catch (err) { console.log('error', err) res = null } return res }
Now we can experiment with the effect:export const upImageToQiniu = async ( loaclFile: string, cb: { (res: any): void; (arg0: any): void }, upConfig: QiNiuUpConfig ) => { const config = new qiniu.conf.Config() const formUploader = new qiniu.form_up.FormUploader(config) const putExtra = new qiniu.form_up.PutExtra() const token = getToken(upConfig.accessKey, upConfig.secretKey, upConfig.scope) let gzipImage if (upConfig.gzip) { gzipImage = await imageGzip(loaclFile) } // 获取当前时间戳 var key = new Date().getTime() // 上传调用方法 const uploadFnName = gzipImage ? 'putStream' : 'putFile' // 上传内容 const uploadItem = gzipImage ? bufferToStream(gzipImage) : loaclFile // 七牛上传 formUploader[uploadFnName]( token, key, uploadItem, putExtra, function (respErr: any, respBody: any, respInfo: any) { if (respErr) { throw respErr } if (respInfo.statusCode === 200) { const url = upConfig.domain + '/' + respBody.key cb(url) } } ) }
Select a png picture on the computer:
## #######After uploading with our plug-in, open the link and take a look: ###############The image is compressed successfully~~#########三, Solving legacy bugs######### I found a problem when using it, that is, sometimes the editor would suddenly become stuck. Later, I found out that the reason was that it would always get stuck when there are spaces in the link, and then hover other content. None responded. So just remove the spaces in the hover string and then execute the following method to get the link: ###// 当前行的文本内容 const currentLineText = document.lineAt(position).text.replace(/\s+/g, "")######4. End############Because when previewing the image in hover In order to prevent some images from being too large and slow to load, Qiniu's cropping parameters have been added, so other types of image links may not be previewable. This will be solved later^ ^. I have uploaded the plug-in source code to ###github###, everyone is welcome to click start^ ^. If you have better ideas for plug-ins, you can also communicate with each other. #########For more programming-related knowledge, please visit: ###Introduction to Programming###! ! ###
The above is the detailed content of How to compress images using Node.js? Method introduction. For more information, please follow other related articles on the PHP Chinese website!