From 7e6a76136396512a74767769bc0ef1887c2c4f62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Ml=C3=A1dek?= Date: Sun, 19 Sep 2021 11:46:49 +0200 Subject: [PATCH] lazy load images in deno --- cli/collages.ts | 35 +++++++++++++++++++++++++---------- cli/main.ts | 6 +----- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/cli/collages.ts b/cli/collages.ts index 6245b00..3b535b5 100644 --- a/cli/collages.ts +++ b/cli/collages.ts @@ -4,20 +4,35 @@ import { Image, } from "https://deno.land/x/canvas/mod.ts"; import { CollageContext, CollageImage } from "../src/common/types.ts"; +import { init } from "https://deno.land/x/canvas@v1.3.0/mod.ts"; + +const canvasKit = await init(); export class ProxyImage implements CollageImage { - private image: Image; - public readonly height: number; - public readonly width: number; + private filepath: string; + private _image: Image | undefined; - constructor(image: Image) { - this.image = image; - this.width = image.width(); - this.height = image.height(); + constructor(filepath: string) { + this.filepath = filepath; } - public get(): Image { - return this.image; + public get image(): Image { + if (!this._image) { + const image = canvasKit.MakeImageFromEncoded(Deno.readFileSync(this.filepath)) + if (!image) { + throw Error(`Failed loading ${this.filepath}!`); + } + this._image = image; + } + return this._image; + } + + public get width(): number { + return this.image.width(); + } + + public get height(): number { + return this.image.height(); } } @@ -39,6 +54,6 @@ export default class BrowserCollageModes dw: number, dh: number, ): void { - ctx.drawImage(image.get(), sx, sy, sw, sh, dx, dy, dw, dh); + ctx.drawImage(image.image, sx, sy, sw, sh, dx, dy, dw, dh); } } diff --git a/cli/main.ts b/cli/main.ts index 881a1b5..edfd1aa 100644 --- a/cli/main.ts +++ b/cli/main.ts @@ -62,11 +62,7 @@ if (shuffledFiles.length > 25) { shuffledFiles.splice(25, shuffledFiles.length - 25); } -const images: ProxyImage[] = (await Promise.all( - shuffledFiles.map(async (imageURL) => - canvasKit.MakeImageFromEncoded(await Deno.readFile(imageURL)) - ), -)).map((image) => new ProxyImage(image!)); +const images: ProxyImage[] = shuffledFiles.map((file) => new ProxyImage(file)); const modes = new DenoCollageModes();