imagedenoloadimage

deno-canvas loadImage function doesn't seem to work. Has anyone used it successfully?


The deno-canvas loadImage function fails to work for me, see github issue https://github.com/denoland/deno/issues/18876

Has anyone successfully loaded an image using deno-canvas loadImage(url). If so, could you show how?

Here's my test:

// Imports for canvas and image, see docs:
// https://deno.land/x/canvas@v1.4.1
// https://github.com/DjDeveloperr/deno-canvas
import {
    createCanvas,
    loadImage,
} from 'https://deno.land/x/canvas@v1.4.1/mod.ts'

// make sure above works:
console.log('createCanvas', createCanvas)
console.log('loadImage', loadImage)

// create a url to a mozilla image. (Droping the url in browser showed it exists)
const imgPath = 'https://developer.mozilla.org/assets/mdn_contributor.png'
const imgUrl = new URL(imgPath)

console.log('imgPath', imgPath)
console.log('imgUrl', imgUrl)

// load the image using http path. Result is empty object.
let img = await loadImage(imgPath)
console.log('img', img)

// try with Url object. Fails with error
img = await loadImage(imgUrl)
console.log('img', img)
// fails with this stack trace:
// error: Uncaught (in promise) TypeError: url.startsWith is not a function
//   } else if (url.startsWith("http")) {
//                  ^
//     at loadImage (https://deno.land/x/canvas@v1.4.1/src/canvas.ts:23:18)
//     at file:///Users/owen/Dropbox/src/agentscript/tests/denoerror.js:25:13
//     at eventLoopTick (ext:core/01_core.js:165:11)

Solution

  • loadImage expects a string URL, not an URL object.

    Use loadImage(imgUrl.href) instead.

    See https://deno.land/x/canvas@v1.4.1/src/canvas.ts?source#L18

    export async function loadImage(url: string | Uint8Array) {
      let data;
    
      if (url instanceof Uint8Array) {
        data = url;
      } else if (url.startsWith("http")) {
        data = await fetch(url).then((e) => e.arrayBuffer()).then((e) =>
          new Uint8Array(e)
        );
      } else if (url.startsWith("data")) {
        data = dataURLtoFile(url);
      } else {
        data = await Deno.readFile(url);
      }
    
      const img = canvas.MakeImageFromEncoded(data);
      if (!img) throw new Error("Invalid image data");
    
      return img;
    }
    

    It takes either a string URL or image data as Uint8Array.


    deno-canvas provides a working sample with loadImage

    https://deno.land/x/canvas@v1.4.1/examples/image.ts?source