简体   繁体   English

使用JavaScript解码图像

[英]Decode an Image using JavaScript

I have a little generated JavaScript from a JSP page that looks like this: 我从JSP页面生成了一些如下所示的JavaScript:

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. 当用户单击按钮时,将调用上面的代码段,并且step是随函数每次运行而增加的变量。 Image is a Servlet that generates a PNG-encoded Image. Image是一个Servlet,它生成PNG编码的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. 由于我知道可以执行多少步骤,因此我想到了在请求页面时生成图像,并将其嵌入到可能经过Base64编码的JavaScript中,以便可以在所有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. 我不想使用jQuery之类的外部JavaScript框架,也不必在意那些不太常见的浏览器,只要能与Mozilla浏览器和Google Chrome一起使用就足够了。

If you only want to embed the image source into a HTML page, you can do the following: 如果只想将图像源嵌入HTML页面,则可以执行以下操作:

<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. 几乎所有浏览器都支持此功能: http : //caniuse.com/#feat=datauri…对IE的“部分支持”意味着它仅限于图像和CSS,但是图像是我们在这里所做的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM