How to resize image?

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

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 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);

    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 = as string;

Or this …

Basically, you put the image in a canvas element (hidden) and then resize.

1 Like

Hi @Tommertom Thanks so much!!! I will try it and report the result soon! :blush: :vulcan_salute:

1 Like