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

How to solve the 2002 error when installing MySQL database on Alibaba Cloud

The following error occurred while installing the...

JavaScript to achieve the effect of clicking on the self-made menu

This article shares the specific code of JavaScri...

Vue global filter concepts, precautions and basic usage methods

Table of contents 1. The concept of filter 1. Cus...

How to use CocosCreator object pool

Table of contents Preface: Specific operations St...

Do you know how to use vue-cropper to crop pictures in vue?

Table of contents 1. Installation: 2. Use: 3. Bui...

How to configure Java environment variables in Linux system

Configure Java environment variables Here, the en...

Detailed explanation of JavaScript function introduction

Table of contents Function Introduction function ...

Introduction to Docker Architecture

Docker includes three basic concepts: Image: A Do...

Essential conditional query statements for MySQL database

Table of contents 1. Basic grammar 2. Filter by c...

Detailed explanation of nodejs built-in modules

Table of contents Overview 1. Path module 2. Unti...

Implementing a simple calculator based on JavaScript

This article shares the specific code of JavaScri...

Detailed installation and configuration tutorial of MySQL 5.7 under Win10

1. Unzip MySQL 5.7 2. Create a new configuration ...

Vue resets data to its initial state

In some cases, the data in data needs to be reuse...

Detailed explanation of the use cases of Vue listeners

The first one is to use jQuery's ajax to send...