Make images smaller using best-in-class codecs, right in the browser.
JavaScript
Put bitmapToImageData into utils module
Surma5245c5ca6e39
diff --git a/src/components/app/index.tsx b/src/components/app/index.tsxindex 3588cac5..7fade86c 100644--- a/src/components/app/index.tsx+++ b/src/components/app/index.tsx@@ -1,5 +1,5 @@import { h, Component } from 'preact';-import { bind } from '../../lib/util';+import { bind, bitmapToImageData } from '../../lib/util';import * as style from './style.scss';import Output from '../output';@@ -25,27 +25,13 @@ export default class App extends Component<Props, State> {}}- private async getImageData(bitmap: ImageBitmap): Promise<ImageData> {- // Make canvas same size as image- const canvas = document.createElement('canvas');- canvas.width = bitmap.width;- canvas.height = bitmap.height;- // Draw image onto canvas- const ctx = canvas.getContext('2d');- if (!ctx) {- throw new Error("Could not create canvas context");- }- ctx.drawImage(bitmap, 0, 0);- return ctx.getImageData(0, 0, bitmap.width, bitmap.height);- }-@bindasync onFileChange(event: Event) {const fileInput = event.target as HTMLInputElement;if (!fileInput.files || !fileInput.files[0]) return;// TODO: handle decode errorconst bitmap = await createImageBitmap(fileInput.files[0]);- const data = await this.getImageData(bitmap);+ const data = await bitmapToImageData(bitmap);const encoder = new MozJpegEncoder();const compressedData = await encoder.encode(data);const blob = new Blob([compressedData], {type: 'image/jpeg'});diff --git a/src/lib/util.ts b/src/lib/util.tsindex 3ceadea5..3d0e09b7 100644--- a/src/lib/util.ts+++ b/src/lib/util.ts@@ -24,3 +24,22 @@ export function bind(target: any, propertyKey: string, descriptor: PropertyDescr}};}++/**+ * Turns a given `ImageBitmap` into `ImageData`.+ */+export async function bitmapToImageData(bitmap: ImageBitmap): Promise<ImageData> {+ // Make canvas same size as image+ // TODO: Move this off-thread if possible with `OffscreenCanvas` or iFrames?+ const canvas = document.createElement('canvas');+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ // Draw image onto canvas+ const ctx = canvas.getContext('2d');+ if (!ctx) {+ throw new Error("Could not create canvas context");+ }+ ctx.drawImage(bitmap, 0, 0);+ return ctx.getImageData(0, 0, bitmap.width, bitmap.height);+}+