how to clear image variable in javascript - javascript

I have the following UI :
I m checking image resolution on each of the image to be uploaded when they get changed.
//preview image
$(document).on('change', '#product_image', function(event) {
var output = document.getElementById('preview_product_image');
output.src = URL.createObjectURL(event.target.files[0]);
image_check(output,event);
});
//image1
$(document).on('change', '#product_image1', function(event) {
var output = document.getElementById('preview_product_image1');
output.src = URL.createObjectURL(event.target.files[0]);
image_check(output,event);
});
//the resolution check code below
var loaded = false;
function loadHandler(path,width,height) {
if (loaded) {
return;
}
loaded = true;
alert("The image you have selected is low resloution image.Your image width="+width+",Heigh="+height+". Please select image greater or equal to 600x600,Thanks!");
var output = document.getElementById(path);
output.src = "http://localhost/uploads/no-photo.jpg";
}
function image_check(output,event) {
//alert("Image size");
var output = document.getElementById("preview_product_image");
output.src = URL.createObjectURL(event.target.files[0]);
var img = new Image();
img = output;
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
//window.URL.revokeObjectURL( img.src );
if( width < 600 || height < 600 ) {
// alert("The image you have selected is low resloution image.Your image width="+width+",Heigh="+height+". Please select image greater or equal to 255x255,Thanks!");
if(img.complete) {
loadHandler("preview_product_image",width,height);
}
}
};
}
THE PROBLEM IS IT only check for one of them when loaded at first time , later it would not validate for other image preview box .
Please help ?

This has solved the situation , Thanks to all !!
var output = document.getElementById('preview_product_image');
if(this.height < 600 || this.width < 600) {
output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
alert("The image you have selected is low resloution image.Your image width="+this.width+",Heigh="+this.height+". Please select image greater or equal to 600x600,Thanks!");
}
else{
output.src = URL.createObjectURL(event.target.files[0]);
}
return;
}
img.src = URL.createObjectURL(event.target.files[0]);

Related

How can I check image orientation in Angular before uploading image

I just want to image being upload on my website must portrait or square and I don't want to crop image, image to be uploaded must be portrait or square by default I have searched number of website \ number method use but none worked
know I am trying this method but it also not working because it is running async
if give landscape image in given code it runs if which should not run as
hasError must be true but doesn't because if condition run before the above code could complete so what can I do
let hasError = false;
image = event.target.files[0];
if (image) {
var img = new Image();
img.src = window.URL.createObjectURL(image);
img.onload = function () {
height = img.naturalHeight;
width = img.naturalWidth;
console.log(hasError); // prints false
if (height < width) {
hasError = true; // prints true
console.log(hasError);
}
window.URL.revokeObjectURL(img.src);
}
console.log(hasError); //prints flase
}
if(!hasError){
....
}
I think you should create a function and move your image validation into your function and use a callback to find out the image has error or not.
var fileInput = document.querySelector('input[type="file"]');
var preview = document.getElementById('preview'); //img tag
previewImage(function(hasError){
if (!hasError){
//do something
}
});
function previewImage(callback){
fileInput.addEventListener('change', function(e) {
preview.onload = function() {
height = this.naturalHeight;
width = this.naturalWidth;
if (height < width) {
callback(true);
}
window.URL.revokeObjectURL(this.src);
callback(false);
};
var url = URL.createObjectURL(e.target.files[0]);
preview.setAttribute('src', url);
}, false);
}

jQuery File Upload - get size of uploaded images

I am using the jQuery File Upload to upload product images. There are different "types" of images for each product (different size/dimensions).
I have altered the upload template so that a dropdown of possible image types is shown for each file added. Before clicking upload, the user must pick from the dropdown to indicate what image type the file being uploaded is.
Some image types are an exact size, some just have a minimum width. What I want to do is compare the actual image size to the type chosen to validate they are indicating the correct type.
I'm attempting to do this via the "fileuploadsubmit" callback where I have already added a check to make sure an option is selected in the dropdown.
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
$('#uploading_note').removeClass("alert-danger").html("");
var inputs = data.context.find(':input');
if (inputs.filter(function () {
return !this.value && $(this).prop('required');
}).first().focus().length) {
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image Type is required!");
data.context.find('button').prop('disabled', false);
return false;
}
var fixed_dimension = 0;
var wt = 0;
var ht = 0;
var image_size = getImageSize(data,function(width, height) {
wt = width;
ht = height;
console.log (wt+'x'+ht);
return [wt,ht];
});
...........
This is the getImageSize function.
function getImageSize(data,callback){
var img = new Image();
img.src = _URL.createObjectURL(data.files[0]);
img.onload = function () {
var w = this.width;
var h = this.height;
console.log(w+'-getImageSize-'+h);
callback (w,h);
};
}
The console.log() in both output correctly but I can't get these numbers outside the functions to use them. I understand it has to do with the functions be asynchronous but I can't figure out how to get around it. Or maybe there is a better jQuery File Upload built in option I'm missing.
I understand the asynchronous function issue, this one was attempt at finding a solution to validating the image size. I have also attempted to do this in the PHP script. It works in that I can prevent the upload of an image but the user experience is poor. So I am still looking for a solution as to how to do image size validation using jQuery File Upload.
Below is an update version of the code.
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
console.log(data);
$('#uploading_note').removeClass("alert-danger").html("");
var inputs = data.context.find(':input');
if (inputs.filter(function () {
return !this.value && $(this).prop('required');
}).first().focus().length) {
console.log(data.context);
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image Type is required!");
//$('#uploading_note').addClass("alert-danger").html("Image Type is required!");
data.context.find('button').prop('disabled', false);
return false;
}
var fixed_dimension = 0;
var wt = 0;
var ht = 0;
var image_size = getImageSize(data,function(width, height) {
wt = width;
ht = height;
console.log(wt+'-getImageSize-function'+ht);
switch (inputs[0].value){
case "16x9_background":
case "16x9":
var req_width = 1920;
var req_height = 1080;
fixed_dimension = 1;
break;
case "3x4":
var req_width = 1600;
var req_height = 1200;
fixed_dimension = 1;
break;
case "hires":
var req_width = 1400;
var req_height = 0;
break;
case "lowres":
var req_width = 200;
var req_height = 0;
break;
}
if (fixed_dimension){
if (wt != req_width || ht != req_height){
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image dimensions must be exactly "+req_width+"x"+req_height+". This image is "+wt+"x"+ht+". Image not uploaded.");
return false;
}
} else {
if (wt < req_width){
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image dimensions wrong!! Width must be "+req_width+", not "+wt+". Image not uploaded.");
console.log(wt+'x'+ht);
return false;
}
}
d = inputs.serializeArray();
d.push({ name: "folder", value: $('#barcode').val() });
d.push({ name: "stock_num", value: $('#stock_num').val() });
data.formData = d;
console.log(wt+"xxxx"+ht);
data.submit(); // SUMBIT THE FORM
});
console.log(wt+"xxxx"+ht);
console.log("imagesize:"+image_size);
return false; //STOP THE DEFAULT SUBMIT
});
What I ended up doing was removing the actual form submit button and replace it with a button (not type submit) that calls the validation code. If it passes, the form is then submitted normally (via data.submit()), if not it returns the error. I had to remove the file level submit buttons (or I found it easier to do that).
$('#fileupload').fileupload({
url: 'process.php',
previewThumbnail: true,
sequentialUploads: true,
acceptFileTypes: /(\.|\/)(jpe?g|pdf|zip)$/i,
maxChunkSize: 10000000,
add: function (e, data) {
$('#start_upload_button').click(function () {
getImageSize3(data).then(function(dimensions) {
image validation... return false if any errors
data.submit() // submit the form
});

Javascript - if boolean true not working

So, i created the following function to check the file uploaded by user is
1) Image only
2) Size less than maxSize KBs
3) Dimensions less than maxWidth and maxHeight
All else is working fine except that the condition where I check dimensions. The value in dimensions is indeed the correct value but the condition if(dimensions) doesn't run even when dimensions=true.
Is there something I am doing wrong?
var maxThumbnailWidth = '1050';
var maxThumbnailHeight = '700';
var maxThumbnailSize = '60';
function imageFileChecks(file, type) // type here refers to either Image or Banner or Thumbnail
{
var maxSize;
var maxWidth;
var maxHeight;
var dimensions = false;
if (type == 'image') {
maxSize = maxImageSize;
maxWidth = maxImageWidth;
maxHeight = maxImageHeight;
}
if (type == 'banner') {
maxSize = maxBannerSize;
maxWidth = maxBannerWidth;
maxHeight = maxBannerHeight;
}
if (type == 'thumbnail') {
maxSize = maxThumbnailSize;
maxWidth = maxThumbnailWidth;
maxHeight = maxThumbnailHeight;
}
//First check file type.. Allow only images
if (file.type.match('image.*')) {
var size = (file.size / 1024).toFixed(0);
size = parseInt(size);
console.log('size is ' + size + ' and max size is ' + maxSize);
if (size <= maxSize) {
var img = new Image();
img.onload = function() {
var sizes = {
width: this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
//console.log('onload sizes', sizes);
console.log('onload width sizes', sizes.width);
console.log('onload height sizes', sizes.height);
var width = parseInt(sizes.width);
var height = parseInt(sizes.height);
if (width <= maxWidth && height <= maxHeight) {
dimensions = true;
console.log('dimensions = ', dimensions);
}
}
var objectURL = URL.createObjectURL(file);
img.src = objectURL;
if (dimensions) {
alert('here in dimensions true');
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
imageURL = response.url;
alert('all went well and image uploaded!');
return imageURL;
})
})
} else {
return errorMsg = 'Image dimensions not correct!';
}
} else {
return errorMsg = 'Image size not correct!';
}
} else {
return errorMsg = 'Image Type not correct!';
}
}
<div class="form-group">
<label class="col-md-6 col-xs-12 control-label">Thumbnail</label>
<div class="col-md-6 col-xs-12">
<input type="file" id="thumbnail" class="file" required>
<br>
</div>
</div>
<script type="text/javascript">
document.getElementById('thumbnail').onchange = function() {
var file = document.getElementById('thumbnail').files[0];
if (!file) {
console.log("ji");
return;
}
var type = 'thumbnail';
var thumbnailURL = imageFileChecks(file, type);
}
</script>
This seems like an async issue -- your if(dimensions) statement is running before your img.onload function finishes, in which case dimensions would be equal to false when you get to that part in your code, despite the img.onload function and its logic executing correctly.
You could try nesting the if(dimensions) condition in the img.onload function.
You set your dimension property inside the img.onload callback function.
This will not be executed directly. Then you check the value directly below, which will not be set yet. This is the nature of JavaScript: async functions being queued up to run at some time (example when an image finished loading).
To solve your problem, you need to make the rest of your function execute after img load. This can be done with either callback functions or promises.
I would read up on the asynchronous behavior a bit. Sorry for not providing a link, but should be plenty out there!
#William is right.You can handle it like that
function loadImage(src,callback){
var img = new Image();
img.onload = function() {
if (callback) {
callback(img);
}
}
img.src = src;
}

JS onclick Event Handler - Not Responding

What I'm trying to achieve: clicking on any image should either reveal a clear image if image is blurred or blur the image if image is clear
What's happening: clicking on blurred image clears the image, but clicking on it again does nothing. so, clicking on a clear image does not blur it (as it should).
Here's my code:
<script>
window.onload = init;
function init(e) {
var img = document.getElementsByTagName("img");
//var img = document.getElementById('pics');
img[0].onclick = unblur; // <- why not just img.onclick = unblur ??
img[1].onclick = unblur;
img[2].onclick = unblur;
console.log(img);
/*
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
*/
//img.onclick = unblur;
}
function unblur(e) {
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
var imageSource = img.src; //zeroblur.jpg
var clearImg = imageSource.substring(0, imageSource.length - 8);
var unblurredImg = imageId.concat('.jpg'); // zero.jpg
var blurredImg = imageId.concat('blur.jpg'); // zeroblur.jpg
console.log(imageSource);
console.log(img.src);
//console.log(imageSource);
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg; // image is clear, so hide the pic
}
/*
if (img.src == blurredImg) {
img.src = unblurredImg;
}
} */
//}
}
/*
//if (!(imageId instanceof img)) {
if (imageId !== "pics") {
if (img.src == blurredImg) {
img.src = unblurredImg;
} else if (img.src == unblurredImg) {
img.src = blurredImg;
} // image is blurred, so reveal the pic
else {
console.log("hi");
}
//debugger;
}
}
*/
/*
var img = document.getElementById('zero');
img.src = "zero.jpg";
*/
</script>
</head>
<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">
</div>
</body>
</html>
I also noticed that if I switch the conditions in the function, unblur(e), to the following...
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg;
}
there's no response at all if a user clicks on a blurred image, whereas before (code above) the blurred image will at least reveal the cleared image.
Why is this happening? I see no difference between the two, besides just switching the order of the conditions.
There are various mistakes in your example. Take a look at the Code Snippet for a working example of what you are trying to achieve.
As for your comment:
// <- why not just img.onclick = unblur ??
Because document.getElementsByTagName returns an array of elements. Therefore, you must iterate through the elements to apply the onclick handlers to each one.
(function(document) {
var array = document.getElementsByTagName("img");
for (var i = 0; i < array.length; i++) {
array[i].onclick = toggleBlur;
}
function toggleBlur(event) {
var img = event.target;
var oldSrc = img.src; // Save to display in the console
if (img.src.endsWith("blur.jpg")) {
img.src = img.id + ".jpg";
} else {
img.src = img.id + "blur.jpg"
}
console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
}
})(document);
<body>
<div id="pics">
<img id="zero" src="zero.jpg">
<img id="one" src="one.jpg">
<img id="two" src="twoblur.jpg">
</div>
</body>

Resizing dynamic images not working more than one time

I've got a little problem here. I've been trying to do an image gallery with JavaScript but there's something that I got a problem with. I can get the image to resize when the first image load, but as soon as I load another image, it won't resize anymore! Since the user will be able to upload a lot of different size pictures, I really need to make it work.
I've checked for ready-to-use image gallery and such and nothing was doing what I need to do.
Here's my javascript:
function changeCurrentImage(conteneur)
{
var img = conteneur.getElementsByTagName("img");
var imgUrl = img[0].src;
var imgFirstPart = imgUrl.substring(0, imgUrl.lastIndexOf('.') - 9);
var imgLastPart = imgUrl.substring(imgUrl.lastIndexOf('.'));
var currentImg = document.getElementById('currentImage');
currentImg.src = imgFirstPart + "borne" + imgLastPart;
resize(document.getElementById('currentImage'), 375, 655);
}
function resize(img, maxh, maxw) {
var ratio = maxh/maxw;
if (img.height/img.width > ratio){
// height is the problem
if (img.height > maxh){
img.width = Math.round(img.width*(maxh/img.height));
img.height = maxh;
}
} else {
// width is the problem
if (img.width > maxw){
img.height = Math.round(img.height*(maxw/img.width));
img.width = maxw;
}
}
};
Here's the HTML (using ASP.Net Repeater):
<asp:Repeater ID="rptImages" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<a href="#">
<div id="thumbnailImageContainer1" onclick="changeCurrentImage(this)">
<div id="thumbnailImageContainer2">
<img id="thumbnailImage" src="<%# SiteUrl + Eval("ImageThumbnailPath")%>?rn=<%=Random()%>" alt="Photo" onload="resize(this, 60, 105)" />
</div>
</div>
</a>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Most likely the image is not yet downloaded so img.height and img.width are not yet there. Technically you don't need to wait till the whole image is downloaded, you can poll the image in a timer until width and height are non-zero. This sounds messy but can be done nicely if you take the time to do it right. (I have an ImageLoader utility I made for this purpose....has only one timer even if it is handling multiple images at once, and calls a callback function when it has the sizes) I have to disagree with Marcel....client side works great for this sort of thing, and can work even if the images are from a source other than your server.
Edit: add ImageLoader utility:
var ImageLoader = {
maxChecks: 1000,
list: [],
intervalHandle : null,
loadImage : function (callback, url, userdata) {
var img = new Image ();
img.src = url;
if (img.width && img.height) {
callback (img.width, img.height, url, 0, userdata);
}
else {
var obj = {image: img, url: url, callback: callback,
checks: 1, userdata: userdata};
var i;
for (i=0; i < this.list.length; i++) {
if (this.list[i] == null)
break;
}
this.list[i] = obj;
if (!this.intervalHandle)
this.intervalHandle = setInterval(this.interval, 30);
}
},
// called by setInterval
interval : function () {
var count = 0;
var list = ImageLoader.list, item;
for (var i=0; i<list.length; i++) {
item = list[i];
if (item != null) {
if (item.image.width && item.image.height) {
item.callback (item.image.width, item.image.height,
item.url, item.checks, item.userdata);
ImageLoader.list[i] = null;
}
else if (item.checks > ImageLoader.maxChecks) {
item.callback (0, 0, item.url, item.checks, item.userdata);
ImageLoader.list[i] = null;
}
else {
count++;
item.checks++;
}
}
}
if (count == 0) {
ImageLoader.list = [];
clearInterval (ImageLoader.intervalHandle);
delete ImageLoader.intervalHandle;
}
}
};
Example usage:
var callback = function (width, height, url, checks, userdata) {
// show stuff in the title
document.title = "w: " + width + ", h:" + height +
", url:" + url + ", checks:" + checks + ", userdata: " + userdata;
var img = document.createElement("IMG");
img.src = url;
// size it to be 100 px wide, and the correct
// height for its aspect ratio
img.style.width = "100px";
img.style.height = ((height/width)*100) + "px";
document.body.appendChild (img);
};
ImageLoader.loadImage (callback,
"http://upload.wikimedia.org/wikipedia/commons/thumb/" +
"1/19/Caerulea3_crop.jpg/800px-Caerulea3_crop.jpg", 1);
ImageLoader.loadImage (callback,
"http://upload.wikimedia.org/wikipedia/commons/thumb/" +
"8/85/Calliphora_sp_Portrait.jpg/402px-Calliphora_sp_Portrait.jpg", 2);
With the way you have your code setup, I would try and call your resize function from an onload event.
function resize() {
var img = document.getElementById('currentImage');
var maxh = 375;
var maxw = 655;
var ratio = maxh/maxw;
if (img.height/img.width > ratio){
// height is the problem
if (img.height > maxh){
img.width = Math.round(img.width*(maxh/img.height));
img.height = maxh;
}
} else {
// width is the problem
if (img.width > maxw){
img.height = Math.round(img.height*(maxw/img.width));
img.width = maxw;
}
}
};
function changeCurrentImage(conteneur)
{
var img = conteneur.getElementsByTagName("img");
img.onload = resize;
var imgUrl = img[0].src;
var imgFirstPart = imgUrl.substring(0, imgUrl.lastIndexOf('.') - 9);
var imgLastPart = imgUrl.substring(imgUrl.lastIndexOf('.'));
var currentImg = document.getElementById('currentImage');
currentImg.src = imgFirstPart + "borne" + imgLastPart;
}
I would play around with that. Maybe use global variables for your maxH/W and image ID(s);
#Comments: No, I can't do that server side since it would refresh the page everytime someone click on a new image. That would be way too bothersome and annoying for the users.
As for the thumbnails, those image are already saved in the appropriate size. Only the big image that shows is about 33% of its size. Since we already have 3 images PER uploaded images, I didn't want to upload a 4th one for each upload, that would take too much server space!
As for the "currentImage", I forgot to add it, so that might be helful lol:
<div id="currentImageContainer">
<div id="currentImageContainer1">
<div id="currentImageContainer2">
<img id="currentImage" src="#" alt="" onload="resize(this, 375, 655)" />
</div>
</div>
</div>
#rob: I'll try the ImageLoader class, that might do the trick.
I found an alternative that is working really well. Instead of changing that IMG width and height, I delete it and create a new one:
function changeCurrentImage(conteneur)
{
var thumbnailImg = conteneur.getElementsByTagName("img");
var thumbnailImgUrl = thumbnailImg[0].src;
var newImgUrl = thumbnailImgUrl.replace("thumbnail", "borne");
var currentImgDiv = document.getElementById('currentImageContainer2');
var currentImg = currentImgDiv.getElementById("currentImage");
if (currentImg != null)
{
currentImgDiv.removeChild(currentImg);
}
var newImg = document.createElement("img");
newImageDiv = document.getElementById('currentImageContainer2');
newImg.id = "currentImage";
newImg.onload = function() {
Resize(newImg, 375, 655);
newImageDiv.appendChild(newImg);
}
newImg.src = newImgUrl;
}
Also, in case people wonder, you MUST put the .onload before the .src when assigning an a new source for an image!

Categories

Resources