blatoo
March 6, 2022, 3:12am
1
Hi all,
I am doing a diary app, which just let user take a photo or choose an image and then, I will resize the image, so that I can show the image as a thumbnail.
How can I do that with capacitor? (I found a package react-image-file-resizer
, but it only works for web…)
Thanks in advance
Why do u insist having this done by capacitor?
There are plenty js code examples to resize images
blatoo
March 6, 2022, 4:19pm
3
Actually I did it with the react-image-file-resizer
, it is totally fine on the web, but on the phone it doesn’t work.
Can you suggest me other js libraries?
1 Like
This is what I do to resize a file coming from an input-html element type=file
//
// resizing a file from a HTML-input into a newly dimensioned blob
//
export const resizeFile = (file, maxDimensions, callback) => {
const maxWidth = maxDimensions.width;
const maxHeight = maxDimensions.height;
if (!file.type.match(/image.*/)) {
callback(file, false);
return false;
}
if (file.type.match(/image\/gif/)) {
// Not attempting, could be an animated gif
callback(file, false);
// TODO: use https://github.com/antimatter15/whammy to convert gif to webm
return false;
}
const image = document.createElement('img');
image.onload = (imgEvt) => {
console.log('Image onload event', imgEvt);
let width = image.width;
let height = image.height;
let isTooLarge = false;
if (width >= height && width > maxDimensions.width) {
// width is the largest dimension, and it's too big.
height *= maxDimensions.width / width;
width = maxDimensions.width;
isTooLarge = true;
} else if (height > maxDimensions.height) {
// either width wasn't over-size or height is the largest dimension
// and the height is over-size
width *= maxDimensions.height / height;
height = maxDimensions.height;
isTooLarge = true;
}
if (!isTooLarge) {
// early exit; no need to resize
callback(file, false);
return;
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, width, height);
// TODO: remove canvas and image?
canvas.toBlob((blob) => {
callback(blob, true);
}, file.type);
};
const reader = new FileReader();
reader.onload = (evt) => {
console.log('Image reader event', evt);
image.src = evt.target.result as string;
};
reader.readAsDataURL(file);
};
Or this …
Basically, you put the image in a canvas element (hidden) and then resize.
1 Like
blatoo
March 6, 2022, 5:02pm
5
Hi @Tommertom Thanks so much!!! I will try it and report the result soon!
1 Like