Skip to content

Instantly share code, notes, and snippets.

@josephrocca
Last active April 17, 2023 16:10
Show Gist options
  • Save josephrocca/d97e0532f34e1205f4006d45ca909024 to your computer and use it in GitHub Desktop.
Save josephrocca/d97e0532f34e1205f4006d45ca909024 to your computer and use it in GitHub Desktop.
Center crop and bicubic/bilinear/lanczos resize image in JavaScript (using wasm-vips)
// Put this in your HTML to load the `Vips` global: <script src="https://cdn.jsdelivr.net/npm/wasm-vips@0.0.2/lib/vips.js"></script>
const vips = await Vips();
async function resizeAndCenterCrop(blob, resizeType="cubic", size=224) {
// resize types available: cubic, linear, lanczos2, lanczos3, nearest, mitchell
let im1 = vips.Image.newFromBuffer(await blob.arrayBuffer());
// Resize so smallest side is `size` px:
const scale = 224 / Math.min(im1.height, im1.width);
let im2 = im1.resize(scale, { kernel: vips.Kernel[resizeType] });
// crop to `size` x `size`:
let left = (im2.width - size) / 2;
let top = (im2.height - size) / 2;
let im3 = im2.crop(left, top, size, size)
let outBuffer = new Uint8Array(im3.writeToBuffer('.png'));
im1.delete(), im2.delete(), im3.delete();
return new Blob([outBuffer], { type: 'image/png' });
}
// NOTE: As of writing, wasm-vips requires you to manually delete images that are returned by the library,
// which is why I have the `im1.delete(), im2.delete(), im3.delete()` line at the end. More details are
// here: https://github.com/kleisauke/wasm-vips/issues/13#issuecomment-1073246828
// This may change in later versions of wasm-vips.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment