Skip to content

Commit

Permalink
Fixed x and y crop and added new "circle" parameter
Browse files Browse the repository at this point in the history
Circle parameter help you to crop image in proper circle, just put the value of circle true and there you go.
  • Loading branch information
flameface committed Feb 13, 2024
1 parent 957f0ad commit 41cc8ed
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
33 changes: 22 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,42 @@ const { createCanvas, loadImage } = require('@napi-rs/canvas');

async function cropImage({
imagePath,
x,
y,
x = 0,
y = 0,
width,
height,
borderRadius = 0
borderRadius = 0,
circle = false
}) {
try {
const image = await loadImage(imagePath);

if (!width) width = image.width;
if (!height) height = image.height;

// Calculate scale factors
const scaleWidth = width / image.width;
const scaleHeight = height / image.height;
const scaleFactor = Math.max(scaleWidth, scaleHeight);

// Adjust x and y before scaling
x -= (width - image.width * scaleFactor) / 2;
y -= (height - image.height * scaleFactor) / 2;

// Scaled dimensions
const scaledWidth = image.width * scaleFactor;
const scaledHeight = image.height * scaleFactor;

x = (width - scaledWidth) / 2;
y = (height - scaledHeight) / 2;

// Create canvas
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');

if (borderRadius > 0) {
if (circle) { // Crop image into a circle
ctx.beginPath();
ctx.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, Math.PI * 2);
ctx.closePath();
ctx.clip();
} else if (borderRadius > 0) { // Clip with border radius if provided
ctx.beginPath();
ctx.moveTo(borderRadius, 0);
ctx.lineTo(width - borderRadius, 0);
Expand All @@ -42,12 +52,13 @@ async function cropImage({
ctx.clip();
}

// Draw image
ctx.drawImage(image, x, y, scaledWidth, scaledHeight);

return canvas.toBuffer("image/png");
} catch (error) {
throw new Error(error.message);
return canvas.toDataURL("image/png")
} catch (e) {
throw new Error(e.message)
}
}

module.exports = { cropImage };
module.exports = { cropImage };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "cropify",
"types": "./index.d.ts",
"description": "Crop and round image corners seamlessly.",
"version": "1.0.2",
"version": "1.0.3",
"main": "index.js",
"publishConfig": {
"access": "public",
Expand Down

0 comments on commit 41cc8ed

Please sign in to comment.