1

I have a little generated JavaScript from a JSP page that looks like this:

var elem = document.getElementById("image");
elem.src = "Image?step="+step;

The code snippet above is called when the user clicks on a button, and step is a variable that is increased with every run of the function. Image is a Servlet that generates a PNG-encoded Image.

This works, but it is very slow because the Server must generate the Image when the Client wants it. I know I could pre-load the Image, but I thought of a better solution. Since I know how many steps are allowed, I thought of generating the Images when the page is requested, and embed them into the JavaScript, maybe Base64-encoded so that the Image can be viewed on all OS.

Is it possible to do this? If yes, how could I implement it? I don't want to use external JavaScript frameworks like jQuery, and I don't care about browsers that are not really common, it'll be enough if it works with Mozilla browsers and Google Chrome.

3
  • Are you maybe looking for data URIs? en.wikipedia.org/wiki/Data_URI_scheme If not, can you please explain what you mean by „decode an image”? Commented Sep 14, 2014 at 18:10
  • @lxg I thought I already did. I want to write something like var imagestring = <base64-encoded-image> and then decode that image if the browser should show it Commented Sep 14, 2014 at 18:13
  • @lxg The link you posted looks like a good method to do so, but image/png isn't base64-encoded and I want to have it work on multiple OS Commented Sep 14, 2014 at 18:15

1 Answer 1

1

If you only want to embed the image source into a HTML page, you can do the following:

<img id="image" src="" width="100" height="100" alt="" />

<script type='text/javascript'>/* <![CDATA[ */
    var img = '<?php echo base64_encode(file_get_contents('/path/file.png')); ?>'
    document.getElementById('image').src = "data:image/png;base64," + image;
/* ]]> */</script>    

This is supported by pretty much all browsers: http://caniuse.com/#feat=datauri … “Partial support” for IE means that it is limited to images and CSS, but images is what we do here.

Example: http://jsfiddle.net/m869e2ar/1/

Sign up to request clarification or add additional context in comments.

2 Comments

I thought I mentioned in my question that I use JSP, not PHP. It would be <%= Base64.getEncoder().encodeToString(image_data) %>
It's just an example. Basically, you load a binary image file, base64 encode it and dump it into a JS variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.