I am trying to retreive the actual height and width of an image through javascript.
The image source being used in my case is a BLOB which gets generated as soon as a user inserts a file.
Heres my code:
var img = document.createElement('img');
var blob = URL.createObjectURL(e.target.files[0]);
img.src = blob;
console.log(img);
var w = img.width;
var h = img.height;
console.log("NEW IMAGE width", w);
console.log("NEW IMAGE height: ", h);
Here are the logs:
<img src="blob:http%3A//localhost%3A3000/af3e5a35-8c1c-40b5-ad5a-379c3ab1ec1d">
NEW IMAGE width 0
NEW IMAGE height: 0
the blob is correct since I can view the image in my browser.
When I create another image in my console with the same blob and try to retreive the height and width everything works just fine.
But when I try to run it like that in my onChange event form the input i just get 0 for height and width.
you should get size after image loaded:
img.onload = getSize;//measure after loading or you will get 0
Need to take the width and height after the image got loaded. So need to give some time to load the image.Else you will get zero size always.Take the width/height inside onload event.
var img = document.createElement('img');
var blob = URL.createObjectURL(e.target.files[0]);
img.src = blob;
img.onload = function() {
var w = img.width;
var h = img.height;
console.log("NEW IMAGE width", w);
console.log("NEW IMAGE height: ", h);
}
How to get height and width of the image in blob objeact?
example:
$(function(){
$("input[name=file_name]").on('change',function(){
var url = window.URL || window.webkitURL || window.mozURL;
var src = url.createObjectURL($(this)[0].files[0]);
$("#box").html('<img src="'+src+'">');
$("#box img").attr('width','100');
$('img')[0].onload = function() {
console.log($(this).height()); //get image height by jQuery
console.log($(this)[0].height)// get image height by javascript
console.log($(this)[0].naturalHeight);//get real height by javascript
/**
* if you want to get the image's width,you can use following code :
* $(this).width();
* $(this)[0].width;
* $(this)[0].naturalWidth;
*/
};
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file_name">
</form>
<div id="box"></div>
Try loading it first:
img.onload(function() {
var w = img.width;
var h = img.height;
console.log("NEW IMAGE width", w);
console.log("NEW IMAGE height: ", h);
});
Related
I have:
if(window.FileReader) {
reader = new FileReader();
var sendingcontext = sendingcanvas.getContext('2d');
reader.onload = (function(theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function() {
sendingcanvas.width=this.width;
sendingcanvas.height= this.height;
console.log("height: " + sendingcanvas.height + " width: " + sendingcanvas.width)
sendingcontext.drawImage(image, 0,0);
};
});
reader.onloadend = function(e){
showUploadedItem(e.target.result, file.fileName);
}
reader.readAsDataURL(file);
alert(sendingcanvas.toDataURL());
}
I Suppose I don't have to explain what the code does, But what I want is to get the file api image height and width, set it to sendingcanvas and send it to server using ajax by using it's toDataURL(). I know This is weird but If I remove the alert(sendingcanvas.toDataURL()) from my script My server receives an empty image but If I have it in my script In my server the image is exactly how the client have it.
Thanks for everything.
Just want to point out that the image you are uploading is being converted to a png (if that is what you want)The uploaded file is no longer the same as the user selected
Btw, sending a blob is better then uploading a base64 string that is ~3x larger you can use this polyfill to get support for canvas.toBlob(...) in older browsers
This is basicly what you are doing:
function showUploadedItem(image){
document.body.appendChild(image)
}
// Simulate a file (image)
var black_1x1 = new Uint8Array([71,73,70,56,57,97,1,0,1,0,128,0,0,5,4,4,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59])
var file = new Blob([black_1x1], {type:"image/gif"})
console.log(file)
var img = new Image
img.onload = function() {
console.log("height: " + this.height + " width: " + this.width)
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
canvas.width = this.width
canvas.height = this.height
showUploadedItem(this)
ctx.drawImage(this, 0, 0)
canvas.toBlob(function(blob){
console.log(blob)
// Send the canvas pic to server (using fetch, xhr or jQuery
// With or without FormData
// fetch('/upload', {method: 'post', body: blob})
})
}
// No need to use fileReader + base64
img.src = URL.createObjectURL(file)
/* Just to make the pixel more vissible */
body img {
width: 10px
}
<!-- toBlob polyfill -->
<script src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>
You can try let the image in a <img> tag and get the real width and size of the image in case what you having a DOM:
var height = $( "#main-reference" ).get( 0 ).naturalWidth;
var width = $( "#main-reference" ).get( 0 ).naturalHeight;
this property gives you the real height and width of the img although you have broken the img with css
I have been trying to setup up an app to allow user to capture a photo and preview on canvas before uploading. So far i have been able to capture image and place onto canvas(android chrome), but when it comes to ios using safari i am having no such luck (tried Ipad, 5C)
here is the script i have manage to piece together thanks to the help of stackoverflow community (many thanks)
The issue I am having is that when i choose selected image it should display in my iframe (as it does in chrome) when i try safari it shows no image after selecting
here is a sample link to my app
SampleAPP
HTML
<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
JAVASCRIPT
<script>
function handleFiles()
{
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
var canvas = document.createElement("canvas");
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
document.getElementById('image').src = dataurl;
}
// Load files into file reader
reader.readAsDataURL(file);
// Post the data
/*
var fd = new FormData();
fd.append("name", "some_filename.jpg");
fd.append("image", dataurl);
fd.append("info", "lah_de_dah");
*/
}
</script>
You can remove using <canvas> and set existing <img> src to e.target.result : data URI of uploaded File object at FileReader() load event.
You can defined variable width, use if condition at #image load event when new src is set to check #image .naturalWidth property, if value is greater than width , set #image.width to width variable.
<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>
var img = document.getElementById("image");
var width = 400;
function handleFiles() {
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e) {
img.onload = function() {
if (this.naturalWidth > width) {
this.width = width;
}
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
}
</script>
I am trying to add an image cropper to my site, while also sending the image dimensions for processing when the image is sent to be cropped. I can get the image to show up in the preview box, but I cannot get javascript to output my image dimensions.
My script is:
<script type="text/javascript">
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("id_avatar").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("avatar_preview").src = oFREvent.target.result;
};
var imgheight;
var imgwidth;
function getDimensions() {
imgheight = image.height;
imgwidth = image.width;
document.getElementById('image_dimension').value = ('The image size is ' + imgwidth + ' x ' + imgheight );
};
var image = new Image();
image.src = document.getElementById('avatar_preview').src;
image.onload = getDimensions();
};
</script>
And my HTML:
<input type='file' id='id_avatar' name='avatar' onchange="PreviewImage();" /><br />
<div id="parent" style="width: 300px; height: 300px; overflow: hidden;">
<img id="avatar_preview" src="#" alt="your image" style="width:400px;" />
</div>
<input type='text' id='image_dimension' name='image_dimension' />
This code gives me "This image is 0 x 0" in the image_dimension text field.
You are on the right path but you need to use the Image object.
Instead of
var image = document.getElementById('avatar_preview').src;
You should do
var image = new Image();
image.src = document.getElementById('avatar_preview').src;
Finally, you should leave your onload callback as is.
As a side note, you should insert this line
document.getElementById('image_dimension').value = ('The image size is ' + imgwidth + ' x ' + imgheight );
inside the callback function as the image is loaded asynchronously.
Check out
How to get image size (height & width) using JavaScript?
and https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
This is how you get the image size using Javascript.
1. Instantiate a new Image:
var img = new Image();
2. Set the image source:
img.src = document.getElementById('avatar_preview').src;
3. Now to get the width and height just use:
img.width
img.height
Is there anyway I can get the current height of a responsive div's background-image?
I can get the image's actual size like this:
var img = new Image;
img.src = $('#div').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
...but that doesn't tell me the size of the image after a screen resize (the background-image is set to 100%, and so scales as the window is resized)
Any ideas?
You could calculate the actual height from the div's width:
var img = new Image;
img.src = $('#div').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;
var divWidth = $('#div').width();
var realImgHeight = ( bgImgHeight / bgImgWidth) * divWidth;
I'm trying to load an image from a given link
var imgPath = $(imgLink).attr('href');
and append it to the page, so I can insert it into a given element for an image viewer.
Even though I searched Stackoverflow and the jQuery docs without end, I can't figure it out.
After I load the image, I want to set different values to it, like width, height, etc.
Update:
This is what I got. The problem I'm having is that I can't run jQuery functions on the img element.
function imagePostition(imgLink) {
// Load the image we want to display from the given <a> link
// Load the image path form the link
var imgPath = $(imgLink).attr('href');
// Add image to html
$('<img src="'+ imgPath +'" class="original">').load(function() {
$(imgLink).append(this);
var img = this;
// Resize the image to the window width
// http://stackoverflow.com/questions/1143517/jquery-resizing-image
var maxWidth = $(window).width(); // window width
var maxHeight = $(window).height(); // window height
var imgWidth = img.width; // image width
var imgHeight = img.height; // image height
var ratio = 0; // resize ration
var topPosition = 0; // top image position
var leftPostition = 0; // left image postiton
// calculate image dimension
if (imgWidth > maxWidth) {
ratio = imgHeight / imgWidth;
imgWidth = maxWidth;
imgHeight = (maxWidth * ratio);
}
else if (imgHeight > maxHeight) {
ratio = imgWidth / imgHeight;
imgWidth = (maxHeight * ratio);
imgHeight = maxHeight;
}
// calculate image position
// check if the window is larger than the image
// y position
if(maxHeight > imgHeight) {
topPosition = (maxHeight / 2) - (imgHeight / 2);
}
// x position
if(maxWidth > imgWidth) {
leftPostition = (maxWidth / 2) - (imgWidth / 2);
}
$(imgLink).append(img);
// Set absolute image position
img.css("top", topPosition);
img.css("left", leftPostition);
// Set image width and height
img.attr('width', imgWidth);
img.attr('height', imgHeight);
// Add backdrop
$('body').prepend('<div id="backdrop"></div>');
// Set backdrop size
$("#backdrop").css("width", maxWidth);
$("#backdrop").css("height", maxHeight);
// reveal image
img.animate({opacity: 1}, 100)
img.show()
});
};
$('<img src="'+ imgPath +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
If you want to do for several images then:
function loadImage(path, width, height, target) {
$('<img src="'+ path +'">').load(function() {
$(this).width(width).height(height).appendTo(target);
});
}
Use:
loadImage(imgPath, 800, 800, '#some_target');
Here is the code I use when I want to preload images before appending them to the page.
It is also important to check if the image is already loaded from the cache (for IE).
//create image to preload:
var imgPreload = new Image();
$(imgPreload).attr({
src: photoUrl
});
//check if the image is already loaded (cached):
if (imgPreload.complete || imgPreload.readyState === 4) {
//image loaded:
//your code here to insert image into page
} else {
//go fetch the image:
$(imgPreload).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
} else {
//image loaded:
//your code here to insert image into page
}
});
}
var img = new Image();
$(img).load(function(){
$('.container').append($(this));
}).attr({
src: someRemoteImage
}).error(function(){
//do something if image cannot load
});
after you get the image path, try either of following ways
(as you need to set more attr than just the src)
build the html and replace to the target region
$('#target_div').html('<img src="'+ imgPaht +'" width=100 height=100 alt="Hello Image" />');
you may need to add some delay if changing the "SRC" attr
setTimeout(function(){///this function fire after 1ms delay
$('#target_img_tag_id').attr('src',imgPaht);
}, 1);
I imagine that you define your image something like this:
<img id="image_portrait" src="" alt="chef etat" width="120" height="135" />
You can simply load/update image for this tag and chage/set atts (width,height):
var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
With jQuery 3.x use something like:
$('<img src="'+ imgPath +'">').on('load', function() {
$(this).width(some).height(some).appendTo('#some_target');
});