Luke Vanzweden
Luke Vanzweden

Reputation: 646

How to pass image data to img tag?

I have the following html element:

<img src='profilePic?userName' class='form-avatar'></img>

my controller has this method:

        [System.Web.Mvc.HttpGet]
        public async Task<ActionResult> profilePic()
        {
            string userName = Request.Url.ToString().Split('?').Last();

            string profilePic = await GraphHelper.GetProfilePicAsync(userName);

            return Content(profilePic);
        }

the contents of profilePic are

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

but the image tag does not load the image, and when I inspect it, it shows:

<img src='profilePic?userName' class='form-avatar'></img>

when what I want is

<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' class='form-avatar'></img>

How do I acheive this?

Upvotes: 0

Views: 2524

Answers (2)

Slava Knyazev
Slava Knyazev

Reputation: 6083

"data:image/png;base64,..." is a base64 encoding of an image which allows you to embed it directly in HTML. If you instead want to reference it by URL, you will need to return the actual binary information in raw form by converting it from base64.

// Your code
var profilePicEncoded = profilePic.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(profilePicEncoded);
return File(bytes , "image/png");

This will return a binary png image, which can then be freely embedded.

Upvotes: 1

Caius Jard
Caius Jard

Reputation: 74710

Ehhhrm.. this won't work because when you do something like this:

<img src="http://blah.com/logo.png">

Your browser does not download logo.png, base64 it, insert it into the src attribute in the DOM, then interpret it and display it

Said another way, into src you either put:

  • a url, like "http://yourhost.com/api/path/to/your/controller/action"
  • base64 encoded data, like "data:...."

If you do the latter, then the base64 png data would be inserted into the html at the time the html is sent to the browser..

Upvotes: 0

Related Questions