From 41cc8edff75ee5783d3ceaffb773846c36e3c9aa Mon Sep 17 00:00:00 2001 From: FlameFace Date: Tue, 13 Feb 2024 11:26:41 +0530 Subject: [PATCH] Fixed x and y crop and added new "circle" parameter Circle parameter help you to crop image in proper circle, just put the value of circle true and there you go. --- index.js | 33 ++++++++++++++++++++++----------- package.json | 2 +- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 4057e11..f9109c5 100644 --- a/index.js +++ b/index.js @@ -2,11 +2,12 @@ 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); @@ -14,20 +15,29 @@ async function cropImage({ 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); @@ -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 }; \ No newline at end of file diff --git a/package.json b/package.json index f22ed93..6663b8f 100644 --- a/package.json +++ b/package.json @@ -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",