I am trying to crop a photo using the expo-image-manipulator
method manipulateAsync()
. It takes an argument to for “crop” actions:
{
crop: {
originX: number;
originY: number;
width: number;
height: number;
},
I want to crop so that we only take the middle 50% height of the image (width remains), and the output is 1000px x 1000px height & width, however, we need to keep in mind the aspect ratio of the final image.
async function cropAndResizeImage({
photoUri,
photoWidth,
photoHeight,
}: {
photoUri: string;
photoWidth: number;
photoHeight: number;
}) {
// Calculate the crop dimensions to remove top and bottom 25%
const cropOriginX = 0;
const cropOriginY = photoHeight * 0.25; // Start cropping at 25% height
const cropHeight = photoHeight * 0.5; // Keep the middle 50% of the height
const cropWidth = photoWidth; // Keep the full width
// Ensure the crop rectangle is inside the source image
if (cropOriginX + cropWidth > photoWidth) {
throw new Error('Invalid crop width: exceeds image bounds');
}
if (cropOriginY + cropHeight > photoHeight) {
throw new Error('Invalid crop height: exceeds image bounds');
}
// Calculate the new dimensions to preserve aspect ratio
const aspectRatio = cropWidth / cropHeight;
let newWidth = 1000;
let newHeight = 1000;
if (aspectRatio > 1) {
// Wider than tall
newHeight = newWidth / aspectRatio;
} else {
// Taller than wide or square
newWidth = newHeight * aspectRatio;
}
// Perform the crop and resize
const actions = [
{
crop: {
originX: cropOriginX,
originY: cropOriginY,
width: cropWidth,
height: cropHeight,
},
},
{
resize: {
width: newWidth,
height: newHeight,
},
},
];
const result = await manipulateAsync(photoUri, actions);
return result;
}
However, the output is resulting in error:
Invalid crop options has been passed. Please make sure the requested crop rectangle is inside source image
Here is a log of actions & original photo height/width:
{"photoHeight":2376,"photoWidth":4224,"actions":[{"crop":{"originX":0,"originY":594,"width":4224,"height":1188}},{"resize":{"width":1000,"height":281.25}}]}```
What am i doing wrong?