Skip to content

Getting "instance is disposed" or empty data array errors while handling some JPGs #143

Description

@tremppu

magick-wasm version

0.0.28

Description

When optimizing some JPGs I think the instance gets disposed before it's ready.

Steps to Reproduce

Here is a code snippet that works with most JPGs but not with some:

import {
  initializeImageMagick,
  ImageMagick,
  MagickFormat,
} from '@imagemagick/magick-wasm';

const wasmLocation = new URL(
  '@imagemagick/magick-wasm/magick.wasm',
  import.meta.url
);

interface MagicResponse {
  file: File;
  extension: string;
  originalFile: File;
}

interface ImageSettings {
  targetSize: number;
  width: number;
  height: number;
}

export const doMagic = async (
  originalFile: File,
  settings: ImageSettings
): Promise<MagicResponse> => {
  const { targetSize = 500, width = 3840, height = 3840 } = settings;

  await initializeImageMagick(wasmLocation);
  const sourceBytes = new Uint8Array(await originalFile.arrayBuffer());
  return new Promise((resolve) => {
    ImageMagick.read(sourceBytes, async (magicFile) => {
      const file = await new Promise<File>((resolveFile) => {
        const format = MagickFormat.Jpg;
        const targetSizeBytes = String(targetSize * 1024);
        const maxWidth = Math.min(width, magicFile.width);
        const maxHeight = Math.min(height, magicFile.height);
        magicFile.resize(maxWidth, maxHeight);
        magicFile.quality = 95;
        magicFile.settings.setDefine('jpeg:extent', targetSizeBytes);
        magicFile.write(format, (dataArray) => {
          if (!dataArray.length) throw new Error('Error while writing!');

          const asFile = new File([dataArray], originalFile.name, {
            type: 'image/jpeg',
          });
          resolveFile(asFile);
        });
      });

      return resolve({ file, extension: '.jpg', originalFile });
    });
  });
};

This code should result into "instance is disposed" but if the "magicFile.quality = 95" is commented out it results into empty data.

Images

Here is a Google Drive link since the image that is not working was too large for upload: https://drive.google.com/drive/folders/1KCeiBcSYQAh5zK2yaE4CmlJmgMYkm6aj
ps. large image is not the problem, I have been able to handle even larger files.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions