feat: auto crop uploaded image around face to satisfy perfect corp 60 percent width requirement
This commit is contained in:
+49
-1
@@ -309,10 +309,58 @@ const App = () => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// --- Detect Face and Auto-Crop ---
|
||||
let processedFile = file;
|
||||
try {
|
||||
const img = new Image();
|
||||
const imgUrl = URL.createObjectURL(file);
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve;
|
||||
img.onerror = reject;
|
||||
img.src = imgUrl;
|
||||
});
|
||||
|
||||
// Run face detection on the static image
|
||||
const detections = await skinapi.detectSingleFace(img, new skinapi.TinyFaceDetectorOptions());
|
||||
if (detections) {
|
||||
const { x, y, width: fw, height: fh } = detections.box;
|
||||
|
||||
// Target width should be such that the face takes up 65% of the width
|
||||
// fw / target_width = 0.65 => target_width = fw / 0.65
|
||||
const targetWidth = Math.min(img.width, fw / 0.65);
|
||||
|
||||
// Let's make it a square crop for best results, or keep original aspect ratio if possible
|
||||
// But PerfectCorp just needs face to be large. Let's do a slightly taller rectangle or square.
|
||||
const targetHeight = Math.min(img.height, targetWidth * 1.2);
|
||||
|
||||
const centerX = x + fw / 2;
|
||||
const centerY = y + fh / 2;
|
||||
|
||||
let cropX = Math.max(0, centerX - targetWidth / 2);
|
||||
let cropY = Math.max(0, centerY - targetHeight / 2);
|
||||
|
||||
// Adjust if crop goes out of bounds
|
||||
if (cropX + targetWidth > img.width) cropX = img.width - targetWidth;
|
||||
if (cropY + targetHeight > img.height) cropY = img.height - targetHeight;
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = targetWidth;
|
||||
canvas.height = targetHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(img, cropX, cropY, targetWidth, targetHeight, 0, 0, targetWidth, targetHeight);
|
||||
|
||||
const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.95));
|
||||
processedFile = new File([blob], file.name.replace(/\.\w+$/, '.jpg'), { type: 'image/jpeg' });
|
||||
}
|
||||
URL.revokeObjectURL(imgUrl);
|
||||
} catch (e) {
|
||||
console.warn('Face detection/auto-crop failed, falling back to original image', e);
|
||||
}
|
||||
|
||||
// --- Ensure image meets API min size ---
|
||||
let resized;
|
||||
try {
|
||||
resized = await resizeImageFile(file, 2048, 2048, 1080);
|
||||
resized = await resizeImageFile(processedFile, 2048, 2048, 1080);
|
||||
} catch (e) {
|
||||
throw new Error(`Image resizing failed: ${e.message}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user