Todd Davis
Todd Davis

Reputation: 6033

How to load an HTML5 Canvas with an image from an image-service?

My web app calls a Web API service, which returns an image. The service returns nothing but an image. Calling the service is little different because there is a function in the routing code that adds the required auth-code and such. Anyway, my point is, I don't have the full URL and even if I did, I wouldn't want to pass it into code in plain-text. So what I have is a response, and that response is an image.

    getThumb(filename: string) {
        return this.http.get('/Picture/' + filename).subscribe(response => {
            return response;
        });
  }

What I need to do is draw that image on to a canvas. From what I've seen on the internet so far, it looks like I want to create an image element, then assign that element src a URL, then I can add it to the canvas. It's the src part that's perplexing me. All the samples I see are either loading the image from a local filesystem or predefined URL, or from a base64 string, etc. I can't figure out how to just load an image I have as a response from a service. I'm sure I'm overthinking it.

Does anyone have some sample code to illustrate this?

e.g Something like this:

var img = new Image();   // Create new img element
img.src = ... ; // Set source to image

Upvotes: 0

Views: 41

Answers (1)

Matt Shirley
Matt Shirley

Reputation: 4215

You could convert the image to Base64. In my example, you request the image and convert it to a blob using response.blob(). Once it's a blob, use fileReader.readAsDataURL to get the Base64.

const fileReader = new FileReader();

fetch("image-resource").then((response) => {
    if(response.ok) {
        return response.blob();
    }
}).then((blob) => { 
    fileReader.readAsDataURL(blob);

    fileReader.onloadend = () => {
        console.log(fileReader.result);
    }
});

References:

Upvotes: 1

Related Questions