'How to crop screenshot or image (.png) in nodejs?
- Consider a image file .png
- Consider you have the xy-cords of some element like x:400, y:500
- Consider you have the size of image to be cropped: width: 50, height: 20
I have below snippet from nodejs pack easyimage and I have installed ImageMagick too. When I run below code, it just passes but unable to crop image.
easyimage.crop({
src: 'F:/screenshot.png', //contains fullscreen image
dst: 'F:/screenshot.png', //expect for a new image with cropped name
x: 400,
y: 500,
cropwidth: 50,
cropheight:20,
gravity: 'North-West'
},
function(err, stdout, stderr) {
if (err) throw err;
});
Solution 1:[1]
I use sharp for this and it works pretty well
Try this
const sharp = require('sharp')
sharp('./kangta.jpg')
.extract({ left: 0, top: 0, width: 100, height: 100 })
.toFile('./kangta.new.jpg', function (err) {
if (err) console.log(err);
})
Solution 2:[2]
Here I extend the example given above with a Puppeteer screenshot that gets split/cropped into multiple images with Sharp:
const puppeteer = require('puppeteer');
const sharp = require('sharp');
// original image
let originalImage = 'originalImage.jpg';
// file name for cropped image
let outputImage = 'croppedImage.jpg';
let outputConcat = '';
async function run(){
const browser = await puppeteer.launch({headless:true})
const page = await browser.newPage();
await page.setViewport({
width: 1920,
height: 1080,
deviceScaleFactor: 1,
});
await page.goto('https://en.wikipedia.org/wiki/Main_Page');
await page.screenshot({path: 'originalImage.jpg', fullPage:true});
await browser.close();
var sizeOf = require('image-size');
var dimensions = sizeOf('originalImage.jpg');
console.log(dimensions.width, dimensions.height);
const printText = (newHeight, newTop, imageIndex) => {
console.log('newHeight: ' + newHeight + ', newTop: ' + newTop + ', imageIndex: ' + imageIndex);
};
const cropImage = (newHeight, newTop, imageIndex) => {
sharp('originalImage.jpg')
.extract({left: 0, width: dimensions.width, height: newHeight, top: newTop})
.toFile(outputConcat.concat(imageIndex, outputImage))
};
var remainingTop = dimensions.height;
var cumulitiveTop = 0;
var amountOfImages = Math.ceil(dimensions.height / 1080);
for (let i = 0; i < amountOfImages; i++)
{
if(remainingTop >= 1080)
{
cropImage(1080, cumulitiveTop, i);
//printText(1080, cumulitiveTop, i);
}
else
{
cropImage(remainingTop, dimensions.height - remainingTop, i);
//printText(remainingTop, dimensions.height - remainingTop, i);
break;
}
remainingTop = remainingTop - 1080;
cumulitiveTop += 1080;
}
};
run();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tuan Anh Tran |
| Solution 2 | Ruben 3D Media and Software |
