jQuery - How do I get the image width of an online image? - javascript

I have a project which consists of a HTML, JS and CSS file.
When I open the project in my browser I have an input field (url input), a button and a canvas.
After I insert the URL of an image in the input field and click the button, I want the canvas to resize according to the width and height of the image. Of course, I also want the image to be displayed in the canvas.
Note: Later I want to add a functionality where someone can resize the image with a slider. This means that I really have to save the width of the image in a variable.
So, my main problem is that I don't know how to get the width of that image.
The last thing I tried is the following:
$('#btn_load').click(function () {
input_url = $('#input_url');
var url = input_url.val();
var img_width = url.width;
...
});
Would be glad about some help here, since I tried a lot of stuff in the last hours :)
EDIT:
I now also tried the following:
var inputURL, imgWidth;
inputURL = $('#input_url');
$('#btn_load').click(function () {
var url = inputURL.val();
var img = new Image();
img.src = url;
img.onload = function () {
imgWidth = img.width;
};
canvas.css({
'background-image': 'url(' + url + ')',
//'background-size': 'cover',
});
//This is just to check the width value
inputURL.val(imgWidth + url);
});
But still doesn't work.

This will get the img width and height in the global variables 'imgHeight' and 'imgWidth' It will also display the image on the screen, width a slider to make it bigger or smaller,
the min and max value of the input type range are dynamically set to the original width and height divider by 2 or for the maximum multiplied by 2.
Javascript:
var imgHeight;
var imgWidth;
var img = new Image();
function LoadImage() {
input_url = $('#input_url');
img.src = input_url.val();
//img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
//alert(imgHeight + " : " + imgWidth);
//Now set the image to html
document.getElementById("imgID").src=img.src;
//Now set the dimensions.
$("#imgID").css({'height' : imgHeight+'px', 'width' : imgWidth+'px'});
//Now set the range min to imgwidth / 2. and the max to imgwidth * 2
document.getElementById("range").min = imgWidth / 2;
document.getElementById("range").max = imgWidth * 2;
document.getElementById("range").value = imgWidth;
}
}
function ChangeImageSize(value) {
//Calculate new height so the image doesn't get stretched.
newHeight = value / imgWidth * imgHeight;
//Set the new width and height
$("#imgID").css({'height' : newHeight+'px', 'width' : value+'px'});
}
HTML
<button onclick="LoadImage()">click me</button>
<input type="range" id="range" oninput="ChangeImageSize(this.value)">
<input type="text" id="input_url">
<img id="imgID">

<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" > </script>
<script>
function loadUrl() {
//You can get the value of your url_input and use it instead.
var url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"; //You can take it from your input_url
$("#img-size").attr("src", url);
};
function imageLoaded(sender){
alert($(sender).width() + 'x' + $(sender).height());
}
</script>
</head>
<body>
<img src="" id="img-size" onload="imageLoaded(this);">
<input type="button" onclick="loadUrl();" id="btn_load" value="Load" />
</body>
</html>

You should load the imag to get its natural width and height :
var img = new Image();
img.src = $('#input_url').val();
img.onload = function () {
imageWidth= img.naturalWidth;
imageHeight = img.naturalHeight;
...
}

Related

Resize image file size by inputted percentage value?

I tried to write script to resize the image file size by the given percentage value. My script is as below:
let canvas;
let array_WH = new Array();
let percent = 50;
let img = new Image();
$(function() {
function ff(height, width, percentage) {
var newHeight = height * (percentage / 100);
var newWidth = width * (percentage / 100);
return [newWidth, newHeight];
}
$("#file_select").change(function(e) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
img.onload = function() {
array_WH = ff(img.width, img.height, percent);
console.log('old width: ' + img.width);
console.log('new width: ' + array_WH[0]);
width = array_WH[0];
height = array_WH[1];
if (canvas) return;
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(this, 0, 0, width, height);
// //Line added
var canvasData = canvas.toDataURL();
// //Line edited
this.src = canvasData;
// //Line added
console.log(canvasData.length * 3 / 4, ' bytes');
document.body.appendChild(this); //remove this if you don't want to show it
}
img.src = e.target.result;
}
fileReader.readAsDataURL(e.target.files[0]);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<h1 class="logo">Upload Picture</h1>
<div id="upload_form_div">
<form id="upload_form" method="POST" enctype="multipart/form-data" action="upload">
<input type="file" name="file" capture="camera" id="file_select" />
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
You can FiddleJs for demo here.
Let's say percentage is 50%, therefore function ff(height, width, percentage) {...} supposed to return new width the half of old width, and new height the half of old height, and consequently, the half size of old image size as a result.
However, it does not works the way it is expected. I tested by uploading image file of 3.00 MB (width: 58000px, height: 3867px), then the function produced new image file of 9.5 MB (width: 1933px, height: 2900px), which is far from correct file size that is 1.5 MB the half of old image size.
How could I correct my function to achieve the expected result by the given percentage? Thanks.
1) Changed order in ff call
array_WH = ff(img.height, img.width, percent);
2) Added parameters: type 'image/jpeg' and quality of jpeg 0.5
var canvasData = canvas.toDataURL('image/jpeg', 0.5)
Here is edited fiddle http://jsfiddle.net/2pu4tmkr/

Get Image Dimensions (Height and Width) Js or jquery

I have searched for this, but every time I implement the code it return 24 as height and width as 237 when I upload 400X400 image.
$(document).on('change','#tt' , function(){
var img = document.getElementById('tt');
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
alert(nheight)
alert(nwidth)
});
<input type="file" id="tt" name="tt" >
Is anyone know how can I get 400 as height and 400 as width in alert box when I upload 400X400 image. Any help is really much appreciated.....
Onchange event of file upload creating a Image object and attach uploaded file object as src to image object and then onload event of image object find height and width of image.
Please check below snippet for more understanding.
var _URL = window.URL || window.webkitURL;
$(document).on('change','#tt' , function(){
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert("width : "+this.width + " and height : " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="tt" name="tt" >
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
will just get you the dimension.
Refer this -
Try
var x = document.getElementById("myImg").naturalWidth;
the naturalHeight property to return the original height of an image, or the height property to set or return the value of the height attribute of an image
http://www.w3schools.com/jsref/prop_img_naturalwidth.asp

Scaling image from input[type=file]

Desired Result: I'm looking to select an image from a file upload form, scale it to a thumbnail and display it.
Problem: The following code does exactly what I want it to, however, I must select the file not once, but twice to see the image preview. (Select image, no display, select same image, I get the scaled display) Everything was working great when I was manually assigning width & height, though now that i'm scaling it - this issue began. I'm in need of a code review! When I comment out the if/if else / else statement and manually assign img.width & img.height to be 75 each, I get the display though it's of course not scaled.
previewFiles = function (file, i) {
preview = function (file) {
// Make sure `file.name` matches our extensions criteria
switch (/\.(jpe?g|png|gif)$/i.test(file.name)) {
case true:
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.src = reader.result;
var width = img.width,
height = img.height,
max_size = 75;
if (width <= max_size && height <= max_size) {
var ratio = 1;
} else if (width > height) {
var ratio = max_size / width;
} else {
var ratio = max_size / height;
}
img.width = Math.round(width * ratio);
img.height = Math.round(height * ratio);
img.title = file.type;
$('div.box.box-primary').find('span.prev').eq(i).append(img);
};
reader.readAsDataURL(file);
break;
default:
$('div.box.box-primary').find('span.prev').eq(i).append('<a class="btn btn-app" href="#"><span class="vl vl-bell-o"></span> Unsupported File</a>');
break;
}
};
preview(file);
};
I have changing the scaling up a bit - tried https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ following this article and I have the same issue. Is the problem due to the fact that i'm not using a canvas? I'm pretty new w/jQuery & javascript - Any help here is greatly appreciated!
I made this snippet that fetches an image, thumbnails it & exports it as an img element.
// limit the image to 150x100 maximum size
var maxW=150;
var maxH=100;
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var img = new Image;
img.onload = function() {
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
var iw=img.width;
var ih=img.height;
var scale=Math.min((maxW/iw),(maxH/ih));
var iwScaled=iw*scale;
var ihScaled=ih*scale;
canvas.width=iwScaled;
canvas.height=ihScaled;
ctx.drawImage(img,0,0,iwScaled,ihScaled);
var thumb=new Image();
thumb.src=canvas.toDataURL();
document.body.appendChild(thumb);
}
img.src = URL.createObjectURL(e.target.files[0]);
}
body{ background-color: ivory; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Select a file to create a thumbnail from</h4>
<input type="file" id="input"/>
<br>

CSS value of a image using JavaScript

I have a image on the website.
i should get the CSS value of Max_width for that image using java script for my Jasmine framework.
Can you please guid me.
Here is the code:
it("Should return Max-width value: '"+width+"'",function(){
var width, item;
item = OpenSpace.getElementById("OpenLayers.Layer.Vector_49_svgRoot");
width = item.max_width;
expect(result).toBe(width);
alert(width);
Thanks
Ravi
clientWidth is the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.
var img = document.getElementById('imageid');
var width = img.clientWidth;
Another solution:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
Hope it works

How to auto resize an image for an image preview on the client side?

I am using this script to display an image preview for users when they register to my site. I have it set to be on the client side. Other-words, the image isn't uploaded for the preview.
Trying to auto resize the image the user selects to maintain it's apect ratio when it is display back on the page. Max size 150x150.
<script type='text/javascript'>
function userImage(file) {
if(document.all)
document.getElementById('showImage').src = file.value;
else
document.getElementById('showImage').src = file.files.item(0).getAsDataURL();
if(document.getElementById('showImage').src.length > 0)
document.getElementById('showImage').style.display = 'block';
}
</script>
<input type='file' name='avatar' onchange='userImage(this);' />
<img id='showImage' style='display:none;' />
Changed the suggestion to a simpler model. Please note that IE may need your site to be in trusted zone to allow it to show the image
<script type='text/javascript'>
function userImage(file) {
var img = document.getElementById("img1");
img.onload=function() { this.parentNode.style.display="" }
img.src=(file.files)?file.files.item(0).getAsDataURL():file.value;
}
</script>
<input type="file" name="avatar" onchange="userImage(this);" />
<div id="showImage" style="display:none" ><img name="img1" id="img1" src="dummy.gif" width="150" /></div>
If you are/can use JQuery. Check this for Getting Proportional width where you pass expected height and calculate proportional width.
function GetWidth(expectedHeight )
{
var width = $("#showImage").width();
var height = $("#showImage").height();
var targetWidth = Math.round(expectedHeight * width / height);
$("#showImage").attr("width", targetWidth );
$("#showImage").attr("width", expectedHeight );
}
with javascript
function GetWidth(expectedHeight )
{
var img = document.createElement("img");
var width = img.width;
var height = img.height;
var targetWidth = Math.round(expectedHeight * width / height);
img.width=targetWidth ;
img.height = expectedHeight ;
}

Categories