Several ways to process images in nodejs, using sharp, jimp, and webconvert

Use sharp

Sharp is a fast and efficient Node.js image processing library that supports image format conversion, size adjustment, compression, cropping, rotation, watermarking and other functions. Here are the basic steps for using the Sharp library:

1. Install the Sharp library

To install the Sharp library, you can use the npm command:

npm install sharp

2. Call the Sharp library

To call the Sharp library in the code, you can first introduce the Sharp library:

const sharp = require('sharp');

3. Image format conversion

Using the Sharp library, you can convert image formats to other formats, such as converting JPEG images to PNG images:

sharp('input.jpg')
  .toFormat('png')
  .toFile('output.png', (err, info) => {
   // 处理错误或完成后的回调函数
});

4. Size adjustment

Using the Sharp library, you can resize the image, for example, adjust the image width to 800 pixels:

sharp('input.png')
  .resize(800, null)
  .toFile('output.png', (err, info) => {
    // 处理错误或完成后的回调函数
  });

5. Compression

Using the Sharp library, you can compress the image file size, for example, compress the image file to 50%:

sharp('input.png')
  .jpeg({ quality: 50 })
  .toFile('output.png', (err, info) => {
    // 处理错误或完成后的回调函数
  });

6. Cropping

Using the Sharp library, you can crop images, for example, to 400x400 pixels:

sharp('input.png')
  .resize(800, 800)
  .extract({ width: 400, height: 400, left: 200, top: 200 })
  .toFile('output.png', (err, info) => {
    // 处理错误或完成后的回调函数
  });

7. Rotate

Using the Sharp library, you can rotate the image, for example, rotate the image 90 degrees counterclockwise:

sharp('input.png')
  .rotate(-90)
  .toFile('output.png', (err, info) => {
    // 处理错误或完成后的回调函数
  });

8. Add watermark

Using the Sharp library, you can add a watermark to an image, for example, add the text "Hello World" to the upper left corner of the image:

sharp('input.png')
  .resize(800, null)
  .overlayWith(Buffer.from('Hello World'), { gravity: 'northwest' })
  .toFile('output.png', (err, info) => {
    // 处理错误或完成后的回调函数
  });

The above are the basic steps for using the Sharp library. The specific use can be adjusted according to specific needs.

Use jimp

Jimp is an image processing library for Node.js. It supports reading, manipulating and saving images in multiple formats, such as PNG, JPEG, BMP, GIF, etc. Here are the basic steps for using Jimp:

1. Install Jimp

Install Jimp via npm command:

npm install jimp

2. Introduce Jimp

Introduce the Jimp module into the code:

const Jimp = require('jimp');

3. Read pictures

Use the Jimp.read() method to read the image and process the image in the callback function:

Jimp.read('path/to/image.png', (err, image) => {
  if (err) throw err;
  // 对图片进行操作
});

4. Manipulate pictures

Jimp supports a variety of operations, such as resizing, cropping, rotating, scaling, filters, and more. Here are some common examples of operations:

// 调整大小
image.resize(200, 200)

// 裁剪
image.crop(10, 10, 100, 100)

// 旋转
image.rotate(45)

// 缩放
image.scale(0.5)

// 滤镜
image.greyscale().blur(5)

5. Save the picture

Use the Jimp.write() method to save the image:

image.write('path/to/new/image.png', (err) => {
  if (err) throw err;
  console.log('Image saved.');
});



####完整代码示例
const Jimp = require('jimp');

Jimp.read('path/to/image.png', (err, image) => {
  if (err) throw err;
  
  image.resize(200, 200)
       .crop(10, 10, 100, 100)
       .rotate(45)
       .scale(0.5)
       .greyscale()
       .blur(5)
       .write('path/to/new/image.png', (err) => {
         if (err) throw err;
         console.log('Image saved.');
       });
});

Use webconvert

webpconvert is a Node.js-based tool for processing WebP images. Use it to convert image formats such as JPEG, PNG, GIF, etc. to WebP image format for better image compression and improved website performance. Here's how to use webpconvert:

1. Install Node.js and npm (if you haven’t already).

2. Open a terminal or command line interface and use npm to install webpconvert:

npm install -g webp-convert

3. The command line syntax to convert an image format to WebP format is as follows:

npm install -g webp-convert

For example, there is a PNG image named "example.png" in the current directory. To convert it to WebP format and output it to "example.webp", you can use the following command:

webpconvert example.png example.webp

4. If needed, you can add some options to adjust the quality and size of the conversion, for example:

- Adjust the output image quality level: use the "-q" or "--quality" option and specify a number between 0 and 100.

webpconvert example.png example.webp -q 80

- Resize the output image: use the '-r' or '--resize' option and specify a percentage or pixel value.

webpconvert example.png example.webp -r 50%

- Convert images and automatically replace original files (requires "-o" or "--overwrite" option).

webpconvert example.png -o

More options and usage can be viewed by running the "webpconvert --help" command.

Using Cropper.js

Cropper.js is an image cropping tool based on the HTML5 canvas element, which allows users to freely choose the size and position of the image. Node.js is a JavaScript running environment based on the Chrome V8 engine, which can run JavaScript code on the server side. Using Cropper.js in Node.js requires installing related dependencies and configuring the server.

Install Cropper.js

Cropper.js can be installed using the npm command:

npm install cropperjs --save

After the installation is complete, Cropper.js can be introduced into the project:

const Cropper = require('cropperjs');

Configure server

In order to use Cropper.js with Node.js, you need to configure the server so that it can access image files. You can use the express framework to create a server:

const express = require('express');
const app = express();

app.use(express.static('public'));

app.listen(3000, () => {
  console.log('Server started on port 3000.');
});

The above code creates an express application named app and sets the public folder in the project root directory as a static folder for storing image files. After the server is started, you can visit ```http://localhost:3000``` in the browser to check whether the configuration is successful.

Using Cropper.js

Here is sample code for cropping an image using Cropper.js:

const express = require('express');
const app = express();
const path = require('path');

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/crop', (req, res) => {
  const cropper = new Cropper(req.body.src, {
    aspectRatio: 1 / 1,
    crop(event) {
      console.log(event.detail.x);
      console.log(event.detail.y);
      console.log(event.detail.width);
      console.log(event.detail.height);
    },
  });

  cropper.getCroppedCanvas().toBlob((blob) => {
    res.send(blob);
  });
});

app.listen(3000, () => {
  console.log('Server started on port 3000.');
});

This code creates a Cropper instance named cropper for cropping the image. Among them, ```req.body.src``` represents the path of the image to be cropped, ```aspectRatio``` represents the aspect ratio of the cropping box, and ```crop``` is a callback function used to When the cropping frame changes, the coordinates and size of the cropping frame are output.

After the cropping is completed, use the ```getCroppedCanvas()``` method to output the cropped image as a canvas element, then use the ```toBlob()``` method to convert the canvas element into a Blob object, and finally convert the Blob The object is sent to the client via an HTTP response.

Precautions

There are a few things to note when using Cropper.js:

1. The image must be loaded before it can be cropped, otherwise an error will occur;
2. The cropped image will be sent to the client through an HTTP response, and the correct settings need to be set. MIME type;
3. Cropper.js relies on the canvas element of HTML5 and does not support browsers IE8 and below.
 

Guess you like

Origin blog.csdn.net/zrc_xiaoguo/article/details/134014196