How to use Node.js to determine whether a png image has transparent pixels

How to use Node.js to determine whether a png image has transparent pixels

background

PNG images take up more storage space than jpg images, but the quality of PNG images is significantly better. Sometimes the image quality does not need to be very good, but in order to reduce the package size, some optimization is needed, such as compressing the image and converting png images without transparent pixels into jpg format. This article mainly talks about how to use Node.js to detect png images without transparent pixels and how to convert them into jpg images.

Code

Directly on the code

import canvas from 'canvas';
import fs from 'fs';

/**
 * Determine whether there are transparent pixels in the png image*
 * @param {*} pngPath png image path * @param {number} [limit=255] transparent pixel limit, by default less than 255 is considered transparent pixels * @param {boolean} [isToJpg=false] if there is no transparent pixel, whether to convert to jpg image * @returns
 */
function hasOpacity(pngPath, limit = 255, isToJpg = false) {
  // Get the image buffer
  const buffer = fs.readFileSync(pngPath);

  // The width of the image is stored in the 17th to 20th bytes of the buffer const width = buffer.readUInt32BE(16);
  // The width of the image is stored in the 21st to 24th bytes of the buffer const height = buffer.readUInt32BE(20);

  // Create a canvas const pngCanvas = canvas.createCanvas(width, height);
  // Get the brush const context = pngCanvas.getContext('2d');
  // Create an image const img = new canvas.Image();
  // Record the image img.src = buffer;
  // Use the brush to draw the picture on the canvas context.drawImage(img, 0, 0, width, height);

  // Get the pixel data of the png image let res = context.getImageData(0, 0, width, height);
  let imgData = res.data;
  // Each pixel takes up 4 bytes, calculate how many pixels there are in total // [r, g, b, a]
  let piexCount = imgData.length / 4;

  // Have transparent pixels been found? let isOpacity = false;

  for (let i = 0; i < piexCount; i++) {
    // Traverse each pixel and find the transparent channel let opacity = imgData[i * 4 + 3];
    if (opacity < limit) {
        // If it is less than limit, there are transparent pixels and exit isOpacity = true;
      break;
    }
  }

  // If there are no transparent pixels and isToJpg is true, convert the image to jpg format if (!isOpacity && isToJpg) {
    const out = fs.createWriteStream(pngPath.split('.')[0] + '.jpg');
    pngCanvas.createJPEGStream().pipe(out);
    out.on('finish', () => console.log(pngPath, 'Converted to jpg successfully'));
  }

  // return return isOpacity;
}

console.log(hasOpacity('hh.png', 254, true));
console.log(hasOpacity('jj.png'));

principle:

Canvas uses four bytes to store pixels, [r, g, b, a], representing the red channel, green channel, blue channel, and transparent channel respectively. Each byte is 8 bits, so the data of each channel is between 0 and 255. For the transparent channel, 255 means completely opaque and 0 means completely transparent. We use Node.js's buffer and canvas to convert the PNG image into pixel data, and then by traversing each transparent channel, we can find out whether the PNG image has transparent pixels.

doubt? Why is there a limit parameter?

This is because in actual applications, there may be a small amount of 254 and 253 transparent pixels, which look like completely opaque pixels, so they are also treated as non-transparent pixels. This should be passed according to the limits that you can accept.

Example pictures

With transparent pixels

No transparent pixels

canvas

For more information about canvas, please refer to www.npmjs.com/package/canvas

Summarize

This concludes this article on how to use Node.js to determine whether there are transparent pixels in a png image. For more information about how to use Node.js to determine whether there are transparent pixels in a png image, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  Tutorial on installing Odoo14 from source code on Ubuntu 18.04

>>:  MySQL Database Iron Laws (Summary)

Recommend

CentOS 6 Compile and install ZLMediaKit analysis

Install ZLMediaKit on centos6 The author of ZLMed...

Detailed explanation of how to use Vue to load weather components

This article shares with you how to use Vue to lo...

Detailed tutorial for installing ffmpeg under Linux

1. Install ffmpeg under centos linux 1. Download ...

mysql8.0.23 msi installation super detailed tutorial

1. Download and install MySql Download MySql data...

Professional and non-professional web design

First of all, the formation of web page style main...

JavaScript to implement the back to top button

This article shares the specific code for JavaScr...

How to modify the time in centos virtual machine

The one above shows the system time, and the one ...

Vue.js $refs usage case explanation

Despite props and events, sometimes you still nee...

Implementation of communication between Vue and Flask

Install axios and implement communication Here we...

Vue implements dynamic query rule generation component

1. Dynamic query rules The dynamic query rules ar...

Use Nginx to build a streaming media server to realize live broadcast function

Written in front In recent years, the live stream...