Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting request headers for remote image requests #2099

Closed
rzumer opened this issue Aug 21, 2022 · 2 comments · Fixed by #2104
Closed

Setting request headers for remote image requests #2099

rzumer opened this issue Aug 21, 2022 · 2 comments · Fixed by #2104

Comments

@rzumer
Copy link

rzumer commented Aug 21, 2022

Issue or Feature

Some websites block image requests made from canvas, for example Wikipedia. From Googling around it may be due to missing or invalid headers, e.g. User-Agent. Is there a way to set them currently? If not, please consider setting sane default headers or allowing the user to specify them for individual requests.

Steps to Reproduce

const Image = require('canvas');

async function getImage(src) {
    return new Promise(resolve => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = err => { console.log(err); resolve(null); };
        img.src = src;
    });
}

// will be null, and 403 error printed out to the console
var img = await getImage("https://upload.wikimedia.org/wikipedia/commons/4/48/Daala_Rainbow_Vomit_Tiger.png");

Your Environment

  • Version of node-canvas (output of npm list canvas or yarn list canvas): [email protected]
  • Environment (e.g. node 4.2.0 on Mac OS X 10.8): node v14.17.3 on Windows 10
@apollisa
Copy link
Contributor

I’m also affected by this; will try to make a quick PR soon

@jimmywarting
Copy link
Contributor

jimmywarting commented Sep 28, 2022

Almost think that a http library and Image shouldn't be part of the canvas core anymore
Think we should have a createImageBitmap function instead.

the way you would do it instead would be to:

import { OffscreenCanvas, createImageBitmap } from 'canvas'

// using NodeJS v18 fetch, undici or node-fetch. or fetch-blob/from.js to get a blob
const blob = await fetch(url).then(res => res.blob())
const bitmap = await createImageBitmap(blob)

// draw bitmap to a new offscreen canvas.
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)
// ...

This way you can make any request you like, changing user agent, Method, credentials etc. also changing accept header to allow for any image/*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants