1

i get the raw image data of a png-image from a webserver, and want to use it as the background image of a div-element. is this possible without saving the data as an image-file first?

user1448982
  • 1,200
  • 3
  • 12
  • 22

2 Answers2

5

Use a data URI:

document.getElementById('e').src = 'data:image/png;base64,ton_of_crap';

In that Wikipedia article, there is code for PHP and Python that outputs base-64 encoded images. You can just shove that into the url() of a CSS file (or the src attribute of a <img /> tag) and it should work.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • the image is not base64 encoded, so i tried to leave the ";base64" out, but nevertheless the image doesnt show... – user1448982 Jun 14 '12 at 06:05
  • It needs to be base64-encoded. By "raw-data" what do you mean? Like the contents of the image file, or a special URL that shows you a generated image? – Blender Jun 14 '12 at 06:07
  • its the contents of the image file starting with ?PNG IHDR (...) – user1448982 Jun 14 '12 at 06:10
  • How exactly do you get the raw data? – Blender Jun 14 '12 at 06:11
  • i get it as response from a REST-Server using ajax – user1448982 Jun 14 '12 at 06:13
  • i'm trying to enode it myself using this encoder now: http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html to set the image i use this code: $(".newsflashImage").css("background-image","url('data:image/png;base64," + encode64(data) + "')"); but it still doesnt work... – user1448982 Jun 14 '12 at 06:24
  • i think the problem now is the base64 encoder as a bas64 encoded image i got from the web works. i also tried this encoder http://www.webtoolkit.info/javascript-base64.html but it still doesnt work. – user1448982 Jun 14 '12 at 06:39
  • i solved the problem by base64 encoding the image on the server, thank you for your help! – user1448982 Jun 14 '12 at 08:03
0

Have you tried (with jQuery):

$('#divID').css("background-image", "url(/myimage.png)");

From Switching a DIV background image with jQuery

Community
  • 1
  • 1
joshschreuder
  • 1,413
  • 2
  • 18
  • 32