Guys i am implementing an upload with resized image preview. the script is working, but the resize function is called many times for each img that i upload... why is this happening?
the example:
http://jsfiddle.net/LL4Dj/
and here's my code:
<form action="action" method="method">
<input type="file" id="uploads" name="img[]" multiple />
<button class="button">Enviar</button>
</form>
<div id="preview"></div>
Script
<script type="text/javascript">
function imageResize(e) {
console.log('TIMES');
var MAXWidthHeight = 100;
var r = MAXWidthHeight / Math.max(this.width, this.height),
w = Math.round(this.width * r),
h = Math.round(this.height * r),
c = document.createElement('canvas');
c.width = w;
c.height = h;
c.getContext("2d").drawImage(this, 0, 0, w, h);
this.src = c.toDataURL();
var li = document.createElement('li');
li.appendChild(this);
document.getElementById('preview').appendChild(li);
}
function previewImages() {
var fileList = this.files;
var anyWindow = window.URL || window.webkitURL;
var len = (fileList.length < 4) ? fileList.length : 4;
for (var i = 0; i < len; i++) {
var objectUrl = anyWindow.createObjectURL(fileList[i]);
var img = new Image();
img.onload = imageResize;
img.src = objectUrl;
window.URL.revokeObjectURL(fileList[i]);
}
}
var inputFile = document.getElementById('uploads');
inputFile.addEventListener('change', previewImages, false);
</script>
Its is happening because of these two lines in your < script >,
var inputFile = document.getElementById('uploads');
inputFile.addEventListener('change', previewImages, false);
When ever an image is selected, the "change" event will be triggered and "previewImages()" function will be called.
Related
I have to change the src of an image using java script and I am pretty sure i hit a road block, in the html I have 3 li elements and in the id is the source of the mouseenter img. I feel like I am close but so far. Heres my code so far. Thanks for any help!
Javascript:
var $ = function (id) {
return document.getElementById(id);};
window.onload = function () {
var links = document.getElementsByTagName("li"),
imgElements = document.getElementsByTagName("img"),
imgNode,
i,
URLone,
URLtwo,
link,
image;
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
}
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
HTML ::
<body>
<section>
<h1>Ram Tap Combined Test</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
Working jQuery :
$(document).ready(function() {
$("#image_rollovers img").each(function() {
var oldURL = $(this).attr("src"); // gets the src attribute
var newURL = $(this).attr("id"); // gets the id attribute
// preload images
var rolloverImage = new Image();
rolloverImage.src = newURL;
$(this).hover(
function() {
$(this).attr("src", newURL); // sets the src attribute
},
function() {
$(this).attr("src", oldURL); // sets the src attribute
}
); // end hover
}); // end each
}); // end ready
for (i = 0; i < imgElements.length; i++) {
(function(imgNode) {
imgNode.addEventListener("mouseenter", function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}, false);
imgNode.addEventListener("mouseout", function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
}, false);
})(imgElements[i]);
}
A couple of problems in your code.
First for loop closing right away, instead should close after your
imgNode.mouseout function
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
}
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
Last for loop runs 6 times but there are only 3 tags in html. When it coming to loop no. 3 it doesn't get any value for link.src.
Also links variable provides a collection of 'li' tags and not 'img', last for loop requires src from link.src which doesn't have any value, need to change
var links = document.getElementsByTagName("li"),
to
var links = document.getElementsByTagName("img"),
Try that. Hopefully after correcting above errors your code should work.
My html:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
My Javascript:
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
Everything makes sense to me but for some reason it is not working. It is only showing the first picture (doesn't cycle through the pictures). Please let me know if you need anything else. Thank you.
you are getting element 'rotator' before document is loaded so it doesn't exist.
Try this:
function start() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 1;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
window.onload=function(){
start();
}
Preload the images:
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstcar.gif" // set image src property to image path, preloading image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcar.gif"
slideimages[2] = new Image()
slideimages[2].src = "thirdcar.gif"
</script>
Display the first image:
<img src="firstcar.gif" id="slide" width="100" height="56" />
Create the slideshow(cycle):
<script type="text/javascript">
//variable that will increment through the images
var step=0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
if (step<2)
step++
else
step=0
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
</script>
This is how you can try...it works fine for me....
<html>
<body>
<img src="file:///C:/Users/Public/Pictures/Sample%20Pictures/test1 (2).jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'file:///C:/Users/Public/Pictures/Sample%20Pictures/';
var delayInSeconds = 5;
var images = ['test1.jpg', 'test1 (2).jpg', 'test1 (3).jpg', 'test1 (4).jpg', 'test1 (5).jpg', 'test1 (6).jpg', 'test1 (7).jpg', 'test1 (8).jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 100);
})();
</script>
</body>
</html>
You try to access the DOM element with the id rotator before it got loaded.
There are two ways to bypass this problem:
You can move your script tag below the img tag, because then the javascript get's execute after the img element has been loaded:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
You can set the onload event handler for the document to your anonymous function (or give it a name if you like):
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
</script>
I have a following code that displays random images from array.
It generates random images, but however it fails to load unique image.
For more info i would like to add that this code is for Solitaire game so i need to generate unique image.
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
for (var i = 2; i < 8; i++) {
var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
var imgArrayCopy = imgArray.slice(0); //make a copy of the array.
for (var i = 2; i < 8; i++) {
var rNumber = Math.floor(Math.random() * imgArrayCopy.length);
var rand = imgArrayCopy.splice(rNumber, 1); //deletes the img from the array and returns it;
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
This should do that.
I'm running following code in both Chrome and Firefox up-to-date versions.
window.onload = function()
{
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e)
{
var fileCount=fileInput.files.length;
for(var i=0;i<fileCount;i++)
{
var file = fileInput.files[i];
var reader = new FileReader();
reader.onload = function(e)
{
var screenshotImage = new Image();
screenshotImage.onload = function()
{
var canvas = document.createElement('canvas');
canvas.id = makeid(5);
var canvasContext = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvasContext.drawImage(this,0,0,this.width, this.height);
var imgd = canvasContext.getImageData(0,0,canvas.width,canvas.height);
imagePxielData.push(imgd.data);
document.body.appendChild(canvas);
}
screenshotImage.src = this.result;
}
reader.readAsDataURL(file);
}
});
}
function readData()
{
for(var i=0;i<imageCount;i++)
{
var imgdata=imagePxielData[i];
tmp=0;
for (var j = 0, n = imgdata.length; j < n; j += 4)
{
var r = imgdata[j];
var g = imgdata[j+1];
var b = imgdata[j+2];
if(tmp<100)
console.log("r=>"+r+"g=>"+g+"b=>"+b);
tmp++;
}
}
}
After running by uploading an image, the first 100 RGB values shows different values in Chrome and Firefox. Chrome shows the correct values and Firefox show different values(incorrect values).
Why is this showing different values ?
How can fix this to display correct RGB values in both Chrome and Firefox ?
Thank you.
The following code should be able to save and load .png image to/from local hard drive.
Saving works fine(at least in chrome) but loading produces wrong url and display nothing..
A little help would be really appreciated!
<html>
<head>
<title></title>
</head>
<body>
<img id="img" /><br>
<input type="button" value="Save" onclick="onSave()" /><br />
<input type="file" onchange="onOpen(event)" /><br />
<script>
onSave = function () {
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 100, 150);
var dataURL = canvas.toDataURL("image/png");
var img64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
var binaryImg = atob(img64);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab]);
var a = document.createElement("a");
a.download = 'Blob_img';
a.innerHTML = "Download File";
a.href = window.webkitURL.createObjectURL(blob);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
onOpen = function (event) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var ab = event.target.result;
var ua = new Uint8Array(ab);
var binaryImg;
for (var i = 0; i < ua.length; i++) {
binaryImg += String.fromCharCode(ua[i]);
}
var img64 = btoa(binaryImg);
var image = new Image();
image.src = 'data:image/png;base64,' + img64;
var img = document.getElementById('img');
img.src = image.src;
}
fileReader.readAsArrayBuffer(event.target.files[0]);
};
</script>
</body>
</html>
Your "load" handler for your FileReader is declared without an event parameter. As a result, it's not going to have access to the file contents.
fileReader.onload = function (event) {
var ab = event.target.result;
Without that parameter, the symbol "event" would refer to the parameter of the enclosing function, and that one won't have the file contents.
Also, I think you don't need to do the base64 encoding/decoding via atob and btoa, because the results of converting the canvas contents to a data URL will be a base64 string anyway.
In case somebody is wondering, there is a simpler way of reading the file:
FileReader.readAsDataURL
Check a working example at https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL.