Reputation: 78545
I want to, from JavaScript, access as a variable the file that is loaded as an image in an img tag.
The reason for this is that I want to be able to copy it to and from variables so that I can , among other things, change the image without reloading it.
Can this be done? If so, how?
Note: I'm slightly more interested in reading the data than writing it.
Upvotes: 6
Views: 4067
Reputation: 41882
// Download the image data using AJAX, I'm using jQuery
var imageData = $.ajax({ url: "MyImage.gif", async: false }).responseText;
// Image data updating magic
imageDataChanged = ChangeImage(imageData);
// Encode to base64, maybe try the webtoolkit.base64.js library
imageDataEncoded = Base64Encode(imageDataChanged);
// Write image data out to browser (FF seems to support this)
document.write('<img src="data:image/gif;base64,' + imageDataEncoded + '">');
Upvotes: 8
Reputation: 102725
If you are using Firefox (and I think Opera and maybe Safari; I can't check right now), you can draw the image on a canvas element and use getImageData.
It would work kind of like this:
var img = document.getElementById("img_id");
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext("2d");
var imageData = context.getImageData(0, 0, context.width, context.height);
// Now imageData is an object with width, height, and data properties.
// imageData.data is an array of pixel values (4 values per pixel in RGBA order)
// Change the top left pixel to red
imageData.data[0] = 255; // red
imageData.data[1] = 0; // green
imageData.data[2] = 0; // blue
imageData.data[3] = 255; // alpha
// Update the canvas
context.putPixelData(imageData, 0, 0);
Once you get the image data, you can calculate the starting index for each pixel:
var index = (y * imageData.width + x) * 4;
and add the offset for each channel (0 for red, 1 for green, 2 for blue, 3 for alpha)
Upvotes: 2
Reputation: 92752
You can try downloading the image using AJAX, but then you might hit cross-domain scripting restrictions.
Of other ways of accessing the image data I'm not aware.
Upvotes: 0
Reputation: 37215
you can draw the image of the img tag onto a HTML canvas using canvas.drawImage
Upvotes: 1
Reputation: 338208
Some browsers support a Base64 encoded string as the img src, but not all. This would look like:
<img src="data:image/gif;base64,R0lGODl......j5+g4JADs=">
When you do it that way, you can at lease fake access the actual data, but as I said it is not 100% supported. Other than that - no way.
The real question is: What are you trying to achieve? Most of the time (95%, probably more) repeated image reloads are caught by the browser cache, in which case just modifying the img.src has the same effect and causes no network traffic (if that's what you are worrying about).
Upvotes: 1