Introduction to jpeg-js
jpeg-js is a powerful JavaScript library for decoding and encoding JPEG image data. It is widely used for client-side image processing tasks because of its efficient performance and ease of use.
APIs and Code Snippets
Decoding a JPEG Image
This is how you can decode a JPEG image from a buffer:
const jpeg = require('jpeg-js'); const fs = require('fs'); const jpegData = fs.readFileSync('path/to/image.jpg'); const rawImageData = jpeg.decode(jpegData); console.log(rawImageData);
Encoding an Image to JPEG
Here’s how you can encode raw image data back to a JPEG format:
const jpeg = require('jpeg-js'); const width = 320; const height = 240; const frameData = new Buffer.alloc(width * height * 4); for (let i = 0; i < width * height * 4; i++) { frameData[i] = i % 256; } const rawImageData = { data: frameData, width: width, height: height }; const jpegImageData = jpeg.encode(rawImageData, 50); // Quality is 50 console.log(jpegImageData);
Getting Image Information
To get information about the JPEG image without decoding it completely:
const jpeg = require('jpeg-js'); const fs = require('fs'); const jpegData = fs.readFileSync('path/to/image.jpg'); const info = jpeg.decode(jpegData, {useTArray: true}); console.log(info.width, info.height);
Application Example
Let's create a simple application that reads a JPEG image, processes it, and then saves the modified version.
const jpeg = require('jpeg-js'); const fs = require('fs'); function modifyImage(filePath) { const jpegData = fs.readFileSync(filePath); const rawImageData = jpeg.decode(jpegData); // Invert colors as an example image processing task for (let i = 0; i < rawImageData.data.length; i += 4) { rawImageData.data[i] = 255 - rawImageData.data[i]; rawImageData.data[i + 1] = 255 - rawImageData.data[i + 1]; rawImageData.data[i + 2] = 255 - rawImageData.data[i + 2]; } const jpegImageData = jpeg.encode(rawImageData, 50); fs.writeFileSync('path/to/processed_image.jpg', jpegImageData.data); } modifyImage('path/to/image.jpg');
Run the above code with Node.js and it will read the image, invert the colors, and save the output to a new file.
Using jpeg-js, you can handle various image processing tasks effectively in your applications.
Hash: 2bc7fed9daf253e36cc8ba317bf8216c025ab2c2fca28a4e8ab2e1c0351fb70f