Home > Web Front-end > JS Tutorial > body text

How to compress images using Node.js? Method introduction

青灯夜游
Release: 2021-07-30 10:27:57
forward
4688 people have browsed it

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!

How to compress images using Node.js? Method introduction

1. Content introduction

How to compress images using Node.js? Method introduction

#. 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 imagesAt first, I planned to use the TinyPNG

API to achieve image compression, but after trying it, I found that the compression speed was extremely slow, and it seemed It still cost money, so I gave up decisively. Use

imagemin instead. There is a pitfall here: because imagemin cannot directly compress images, but needs to rely on imagemin-jpegtran and imagemin-pngquant

, but it cannot be installed when installing

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 computer

libpng .

Install libpng

Directly post the address for installing brew:

zhuanlan.zhihu.com/p/90508170How to compress images using Node.js? Method introduction, just say it to him Basically, you can install brew by typing the command. Finally, we execute

brew install libpng

. After

libpng

is installed successfully, we can install How to compress images using Node.js? Method introductionimagemin-pngquant

in the project.

Code to realize compressed imagesAccording to the requirements, we definitely don’t want him to compress the images and put them in the folder. Instead, we need to get the compressed content directly in the code and upload it directly to Seven cows. Then we need to use imagemin.buffer

. This method receives a

buffer

object and returns a

buffer after compression. We only need to use the compressed buffer directly Uploading to Qiniu, the idea is like this, the following is the code implementation:
// 获取buffer
export const getBufferFromFile = (filePath: string): Promise => {
  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 => {
  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
}
Copy after login

This way we can easily implement image compression, now we rewrite it and upload it to Qiniu: Because there was no compression before, we can Directly upload the file path to Qiniu. After compression, we only have the buffer. We need to upload the buffer to Qiniu:

gzipImage ? 'putStream' : 'putFile', if we get the buffer, use formUploader .putStream, otherwise you only need formUploader.putFile to upload

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)
      }
    }
  )
}
Copy after login
Now we can experiment with the effect:

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, "")
Copy after login
######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!

Related labels:
source:掘金--liangyue
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!