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.
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/
Related
I have an image tag in my HTML code with src containing the path to a local image.
<img alt="abc" src="./images/abc.png" />
Upon clicking the image, I want to call a JavaScript method that will return the buffer data of the image.
Example buffer:
(23234)[234,345,786]
How is it done in pure JavaScript?
You can not read pixels from an image, but you can draw an image to a canvas, and use getImageData to extract an array of the RGBA pixel data. Then it is possible to get color under the mouse cursor.
Notes about the example below:
the image is tiny because getImageData has cross-origin protection, and as uploading images for examples does not seem to be possible, the image is encoded in a data URI
however data URI-s also have cross-origin issues in certain browsers, like IE (it will not with IE as far as I remember). I tested the code with Chrome, so that works for sure, and I think it should work with Firefox too
none of these matters with real life code, so if you get this code out from here, and just write <img src="something.jpg" ... (so hosted locally), it can be a large image and it will work with IE too
there is some race condition here, sometimes I get messages about missing imgready function, so StackOverflow may load the HTML first and inject the scripts later. If you see that message, run the snippet again. With more "traditional" code order (scripts located in head) it could not happen
var imgdata;
function imgready(){
var img=document.getElementById("you");
var cnv=document.createElement("canvas");
var w=cnv.width=img.width;
var h=cnv.height=img.height;
var ctx=cnv.getContext("2d");
ctx.drawImage(img,0,0);
imgdata=ctx.getImageData(0,0,w,h);
}
function mmove(event){
if(!imgdata)return;
var x=event.clientX-event.target.offsetLeft;
var y=event.clientY-event.target.offsetTop;
var offset=(x+y*imgdata.width)*4;
var r=imgdata.data[offset];
var g=imgdata.data[offset+1];
var b=imgdata.data[offset+2];
document.getElementById("logdiv").innerText=x+","+y+" ("+offset+"): r="+r+" g="+g+" b="+b;
var cnv=document.getElementById("colorcnv");
var ctx=cnv.getContext("2d");
ctx.clearRect(0,0,cnv.width,cnv.height);
ctx.fillStyle="rgb("+r+","+g+","+b+")";
ctx.beginPath();
ctx.arc(10,10,10,0,Math.PI*2);
ctx.fill();
}
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggMCgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFAEDBAQFBAUJBQUJFA0LDRQUFBQUExQPFBQUFBQUFBQUFBQUFBQUEBUUFBQVDxQUFA4UFBQVFBEVFBQTFBQUERQU/8AAEQgAFAAUAwERAAIRAQMRAf/EABoAAAEFAQAAAAAAAAAAAAAAAAgEBQYHCQP/xAAnEAABAwMEAQMFAAAAAAAAAAABAgMFBBEhAAYHEmETIjEII0FCof/EABkBAAIDAQAAAAAAAAAAAAAAAAQGAwUHAv/EACwRAAEDAwIDBgcAAAAAAAAAAAECAxEABCExUQUGEkFhweHw8RMiMnGBsdH/2gAMAwEAAhEDEQA/AM6GuRZOaplxjVGyh2oQWkuNEhQxm3m2NVhtUNHrJwKPDql/KBVkO/SDPDa9DKRM9QyMm+EOCLbSUOtNFQBeKrmyR83tnqbXItpbb5nZLpbeaKUyROudojt98VZq4QtKAptYJ1inWqjEsVC2i428WyUF1o3Qu2OyTYYPyNGJV1CRiuYjFRSf4KmuERszcM49RvOzdIJOgj2qhtai0W0KBc6LUW7esgWUkEnsAD1JDOi3evVFgCJ7Z8KqSWmEhwKk7R40SXB3M8NOcPbm2puGoVB1VLQ1b7zTTQSiqZKlOKSwv9VdlC4JTg4CsqTn/HuWb3h9wi4t09SCpIB1IOAOoffAORvGlMVpxVm5a+C4YUAZ79Tj1/aGyOl9xGjbK32XV2ytbIyfFrY8/nW0K5aszmFD8+RpUTfORSrdG5ZvccjGtzM7LTbVBQKYo25Svdq00rVh9toOKV6aPan2psMDGg+GmHFK2FDOfTXCnYQaZN09u1yQrOQQR/dPgSClJ7/36mgN6WvrU2vrcqsPk6kccKVECpUiRX//2Q==" id="you" onload="imgready()" onmousemove="mmove(event)">
<canvas id="colorcnv" width="20" height="20"></canvas><br>
<div id="logdiv"></div>
Modified version of tevemadar's answer that might be usefull:
function imgToBuffer(e){
let cnv=document.createElement("canvas"), w=cnv.width=e.width, h=cnv.height=e.height, ctx=cnv.getContext("2d");
ctx.drawImage(e,0,0);
return getImageData(0,0,w,h)
}
This function simply draws the image element to canvas and returns the image buffer. No extra HTML needed.
To get the ArrayBuffer out of it, use
imgToBuffer(el).data.buffer
how do I set up the variable in order to implement a clickTag in Javascript for an HTML5 banner ad? How do I get a reference to the URL that is set in which the banner clicks out to? I know how to do this in AS3. I'm new to programming & esp to Javascript. I am NOT using Swiffy nor am I using Flash & the <canvas>. I am using Google Web Designer with a generic environment.
inside my function I have
mainCTAClickOut= function (e) {
var clickTag = "?"; //here is where I'm having a problem
window.open(window.clickTag, "_blank");
}
What am I missing?
First on html5 banners there is no more clickTAG variable.
Html5 banner is some sort of Rich Media content which is a little bit different from the old-fashion flash banners.
Instead of clickTag, we have 'Exit' concept in Rich Media(Flash or html)
For html5 Rich Media here is the steps:
You should add the exit button as a div tag with some id like:
<div id="exit_button"> Click to Learn More </div>
Then you should add the function to handle the exit and associate a name to it(This name will be used later on the DoubleClick Studio UI).
function bgExitHandler(e) {
Enabler.exit('Background Exit');
}
3.Bound the function to click event on the div tag
document.getElementById('exit_button').addEventListener('click', bgExitHandler, false);
But remember before the step one you should already added and initialized the 'Enabler':
<script src="https://s0.2mdn.net/ads/studio/Enabler.js"></script>
`// If true, start function. If false, listen for INIT.
window.onload = function() {
if (Enabler.isInitialized()) {
enablerInitHandler();
} else {
Enabler.addEventListener(studio.events.StudioEvent.INIT, enablerInitHandler);
}
}
function enablerInitHandler() {
// Start ad, initialize animation,
// load in your image assets, call Enabler methods,
// and/or include other Studio modules.
// Also, you can start the Polite Load
}`
For a complete guide on how to create html5 banner, please refer to the following link.
https://support.google.com/richmedia/answer/2672545?hl=en&ref_topic=2672541&vid=1-635799307124943767-943471333&rd=1
From my understanding, GWD automatically generates the variable script. GWD makes you do steps via their wizard function and all it asks for is the destination URL which can be altered at any time thereafter.
Heloo Paulette,
I work for a spec database service (called OKNOK) and after studying some media kits, I can say that one way is to specify a global variable called clickTAG
<script>
var clickTAG = "%%DEST_URL_ESC%%";
</script>
And use that where you want to execute the click:
<a href="javascript: window.open(clickTAG, '_blank')">
<img src="image.png"/>
</a>
FOR FLASH CC HTML5 CANVAS USERS
I remember the nightmare of a client breathing down my neck and trying to fin an answer to this question, An I swore when I did I would come on to a site like this and help other poor stressed out developer and animators to solve the problem. So here goes step by step.
In your html5 syntax, in the HEAD section paste the code below:
<script>
var clickTAG = "www.yourURL.com";
</script>
replace the www.yourURL.com with your customers or whatever website you are targeting.
Move into the body section of your HTML and paste the following:
<a href="javascript: window.open(clickTAG, '_blank')">
<img src="image.png"/>
</a>
To target the entire stage of your banner delete the img src="image.png" bit and just place the above code in front of the canvas id="canvas" and finally place /a after the id="canvas" section. and bobs your aunty. You have a working clickTag on your Flash HTML5 canvas.Sorry if the fact you cant use opening and closing tags in these posts makes it harder to understand.
Have Fun Martin!
This may be a dumb question, but I've a real confusion and want to get an opinion from somebody who knows this in-out.
Preloading images can be done either via JavaScript or CSS (to name two which I'm considering). I read the tutorials that if the browser finds the same image path again, it would render the cached image.
If I preload images like:
<img src="../images/bg.jpg" alt="background" width="1" height="1" style='display:none' />
and
<img src="images/bg.jpg" alt="background" />
Similar with javascript:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
preload([
'../img/imageName.jpg',
'img/imageName.jpg' // case when using this script in a different hierarchical level)
]);
Will the second call result into rendering of the image from the cached version or it will not work because the image path specified is different (though ultimately it refers to the same file).
Thanks in advance.
I realise this is and old one but I get this one all the time from interns - so here goes...
Even though the onload function is in the JS file asking/telling the browser to look for the image; it is the browser looking for the image and is telling the JS that the image/s loaded.
So your image path in the JS should be the same as how you would enter it in the HTML.
PS: I noticed in your HTML the image folder is "/images" and in your JS the folder is "/img"
I have an Axis camera which has multiple outputs, one of which is a jpg image. This image is a still taken from the camera at the time you load it up. I would like to implement a way for the image to reload (every 30 seconds) without having to reload the entire page, however, I would like for the code to fully download the image before updating it to avoid having a blank screen.
I have been reading around and the closest thing I found was this post Using AJAX / jQuery to refresh an image but the difference is that the image feed I have is coming from the actual camera itself not a php file. I have tried a couple of ways to get this working with my url but I have failed due to the lack of javascript knowledge.
The code I'm using right now to pull up the image is just a simple image tag...
<img src="[camera ip]/jpg/1/image.jpg">
and any time you refresh the browser window it gives you a snapshot of the current video stream.
Any help would be greatly appreciated!
Regards,
Javier
I couldn't find a webcam online with a refreshing image to test this against, but I think this should to the trick for you... or at least get you really close...
<script>
// URL to your cam image
var cam_image = 'http://absdev.ws:8000/jpg/1/image.jpg';
var buffer = {};
function preload() {
buffer = new Image();
// attaching the seconds breaks cache
buffer.src = cam_image + '?' + (new Date()).getTime();
buffer.onload = function() {
setTimeout(preload, 30000); // 30 seconds refresh
document.getElementById('myimg').src = buffer.src;
}
}
preload();
</script>
If you are working with a static group of pictures - you already know the filenames and it's not going to change - you would load everything into your html initially (that solves the blank screen concern), then use a jquery plugin to rotate/refresh the images at the interval you specify, be it 30 seconds or whatever.
So, your html would look something like this:
<ul>
<li><img src="[camera ip]/jpg/1/image.jpg"></li>
<li><img src="[camera ip]/jpg/2/image.jpg"></li>
<li><img src="[camera ip]/jpg/3/image.jpg"></li>
...
</ul>
And then the plugin would cycle through them.
For plugins, use one of these two:
http://nivo.dev7studios.com/
http://jquery.malsup.com/cycle/
Good luck!
To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
I've tried a number of javascript approaches, but I always run into security errors.
I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
Has anyone done this in a simple, reusable way?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, and can come straight from a local file.
Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />). Here's how you would create previews for image files for it:
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
function myUploadOnChangeFunction() {
if(this.files.length) {
for(var i in this.files) {
var src = createObjectURL(this.files[i]);
var image = new Image();
image.src = src;
// Do whatever you want with your image, it's just like any other image
// but it displays directly from the user machine, not the server!
}
}
}
The first step is finding out the image path. JavaScript is allowed to interrogate the upload control for a filename/path, but (for reasons of security) various browsers show different things to the JS engine than they display to the user - they tend to keep the filename intact so you can at least validate its extension, but you may get c:\fake_path\ or some similarly obfuscated thing prepended to the filename. Trying this on various browsers will give you an idea as to what gets returned as a real path, and what gets faked out, and where.
The second step is displaying the image. It's possible to display local images if you know their paths, via img tags with file:// source URLs, if the user's browser allows the file:// scheme. (Firefox doesn't, by default.) So if you can get the user to tell you what the full path to the image is, you can at least try to load it.
JavaScript has no access to the local file system for security purposes, period.
Here's a jQuery + PHP script for uploading an image an previewing it.
I have only ever seen Java applets that do this, for example, the image uploading applet on Facebook. The downside to the Java approach is that the user will be prompted to trust the applet before it runs, which is a kind of annoyance, but this allows the applet to present a file browser with image previews or do more interesting things like allows the user to upload an entire directory.
You can try this approach, although it seems it doesn't work on IE.
http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/
It's simple and fast to code.
I put the code here just in case the source dies:
Script:
<!-- Assume jQuery is loaded -->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the HTML:
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>