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.
No. There is no text inside the img. According to the specs, the img element is a void element, i.e. it doesn't have any content or an end tag.
The img element has two required attributes: src : The source location (URL) of the image file. alt : The alternate text. This is used to describe the image for someone who cannot see it because they are either using a screen reader or the image src is missing.
The <img> tag has two required attributes: src - Specifies the path to the image. alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed.
The HTML <img> element is found within the <body> tag. The <img> tag has 2 required attributes - src and alt.
// 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 + '">');
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With