Skip to content

Instantly share code, notes, and snippets.

@vagusX
Created December 6, 2023 04:43
Show Gist options
  • Save vagusX/cd04c081a1b2858ff369d4941518bd5c to your computer and use it in GitHub Desktop.
Save vagusX/cd04c081a1b2858ff369d4941518bd5c to your computer and use it in GitHub Desktop.
切掉图片白边.js
// write by openai chatgpt
const Jimp = require('jimp');
Jimp.read('./sample.jpg')
.then((image) => {
const width = image.bitmap.width;
const height = image.bitmap.height;
let left = 0;
let top = 0;
let right = width - 1;
let bottom = height - 1;
// Find left boundary
for (let x = 0; x < width; x++) {
let isEmptyColumn = true;
for (let y = 0; y < height; y++) {
const pixel = Jimp.intToRGBA(image.getPixelColor(x, y));
if (pixel.r !== 255 || pixel.g !== 255 || pixel.b !== 255) {
isEmptyColumn = false;
break;
}
}
if (!isEmptyColumn) {
break;
}
left++;
}
// Find top boundary
for (let y = 0; y < height; y++) {
let isEmptyRow = true;
for (let x = left; x <= right; x++) {
const pixel = Jimp.intToRGBA(image.getPixelColor(x, y));
if (pixel.r !== 255 || pixel.g !== 255 || pixel.b !== 255) {
isEmptyRow = false;
break;
}
}
if (!isEmptyRow) {
break;
}
top++;
}
// Find right boundary
for (let x = width - 1; x >= left; x--) {
let isEmptyColumn = true;
for (let y = top; y <= bottom; y++) {
const pixel = Jimp.intToRGBA(image.getPixelColor(x, y));
if (pixel.r !== 255 || pixel.g !== 255 || pixel.b !== 255) {
isEmptyColumn = false;
break;
}
}
if (!isEmptyColumn) {
break;
}
right--;
}
// Find bottom boundary
for (let y = height - 1; y >= top; y--) {
let isEmptyRow = true;
for (let x = left; x <= right; x++) {
const pixel = Jimp.intToRGBA(image.getPixelColor(x, y));
if (pixel.r !== 255 || pixel.g !== 255 || pixel.b !== 255) {
isEmptyRow = false;
break;
}
}
if (!isEmptyRow) {
break;
}
bottom--;
}
// Crop the image based on the boundaries
image.crop(left, top, right - left + 1, bottom - top + 1);
// Save the cropped image
image.write('./output.jpg');
console.log('Image cropped successfully!');
})
.catch((error) => {
console.error('Error cropping image:', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment