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

Vue implements internationalization of web page language switching

1. Basic steps 1: Install yarn add vue-i18n Creat...

Vue3+el-table realizes row and column conversion

Table of contents Row-Column Conversion Analyze t...

Detailed explanation of using top command to analyze Linux system performance

Introduction to Linux top command The top command...

How to add, delete and modify columns in MySQL database

This article uses an example to describe how to a...

Detailed tutorial on installing mysql 8.0.13 (rpm) on Centos7

yum or rpm? The yum installation method is very c...

Detailed explanation of how to dynamically set the browser title in Vue

Table of contents nonsense text The first router/...

Historical Linux image processing and repair solutions

The ECS cloud server created by the historical Li...

Introduction to root directory expansion under Linux system

1. Check Linux disk status df -lh The lsblk comma...

Nginx reverse proxy and load balancing practice

Reverse Proxy Reverse proxy refers to receiving t...

Tutorial on installing Microsoft TrueType fonts on Ubuntu-based distributions

If you open some Microsoft documents with LibreOf...

MySQL data operation-use of DML statements

illustrate DML (Data Manipulation Language) refer...

How to use and limit props in react

The props of the component (props is an object) F...

Detailed explanation of LVM seamless disk horizontal expansion based on Linux

environment name property CPU x5650 Memory 4G dis...

The problem of Vue+tsx using slot is not replaced

Table of contents Preface Find the problem solve ...

Detailed explanation of the correct use of the if function in MySQL

For what I am going to write today, the program r...