Show Image Preview + Show Dimensions - javascript

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

Related

How to do multiple image resize, preview and upload in a form using javascript

What I need is image upload within a form:
<input type="file" id="files" name="pics[]" multiple />
<br>
<output id="list"></output>
I have read a lot, including:
Image resizing client-side with JavaScript before upload to the server
Show an image preview before upload
https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
Then come up with a solution, but it does not work:
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var img = document.createElement('img');
img.src = e.target.result;
var canvas = document.createElement('canvas');
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
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");
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img class="thumb" src="',
dataurl,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
It won't do resize and won't do preview.
However, multiple full size image upload still works.
EDIT:
It does resize and does preview. But after I click submit the form, the full size original images are still uploaded.
Am I doing something wrong?
Full size original images are submitted because you're not changing the images themselves, rather creating new images. But the <input[file]>still points to the original images. You can ignore these <input[file]> and instead submit the resized image's dataUrl within <form/> possibly through a hidden <input> field.
Simply use the resized images, convert them to base64 dataUrls, write to some hidden inputs within the form to submit.
var dataurl = canvas.toDataURL("image/png");
document.getElementById('hiddenInputForImage').value=dataurl;

How to get file api image size in javascript?

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

image preview before uploading -IOS

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>

Can't get height and width of image in javascript

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);
});

Javascript Resize Image not working

I have JS which resize the width and height of Image which is working fine if I used Alert before assigning the actual image src to the image object and if I omit the alertbox, it is not working. Please suggest me how to fix it.
`
<html>
<head>
<script type="text/javascript" language="javascript">
function resize_image_height_weight(id, hgt, wdth)
{
//alert(id);
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
// alert("Height=>" + heights + " Width=> " + widths);
if(heights > hgt || widths > wdth)
{
if(heights > widths)
{
var temp = heights/hgt;
var new_width = widths / temp;
new_width = parseInt(new_width);
heights = hgt;
widths = new_width;
}
else
{
var temp = widths/wdth;
var new_height = heights / temp;
new_height = parseInt(new_height);
heights = new_height;
widths = wdth;
}
}
Obj.height = heights;
Obj.width = widths;
}
</script>
</head>
<body>
<div>
<center>
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" id="i" alt="Google logo" height="150" width="150">
<script type="text/javascript">
document.images[document.images.length-1].onload = resize_image_height_weight("i",150,150);
</script>
</center>
</div>
</body>
</html>`
When you set the .src on an image, you have to wait until the image is successfully loaded until you can read it's height and width. There is an onload event handler that will tell you when the image is loaded.
Here's a place in your code where this issue could occur:
Obj=document.getElementById(id);
myImage = new Image();
myImage.src = Obj.src;
var heights = myImage.height;
var widths = myImage.width;
In this case, since the image was already elsewhere in the document, you should just read the height and width off the existing element rather than the new element.
Be very careful when testing because if the image is in your browser cache, it may load immediately, but when it's not in your cache, it takes some time to load and won't be available immediately.
Putting an alert at the right place in your script can allow the image to load before the script proceeds which could explain why it works with the alert.
As RobG mentions, your onload handler is also faulty (needs to be a function, not the returned result of a function).
Here's a simpler function to scale an image to fit the bounds. This uses a trick that you only need to set one size (height or width on the image) and the other will be scaled by the browser to preserve the aspect ratio.
function resizeImage(id, maxHeight, maxWidth) {
// assumes the image is already loaded
// assume no height and width is being forced on it yet
var img = document.getElementById(id);
var height = img.height || 0;
var width = img.width || 0;
if (height > maxHeight || width > maxWidth) {
var aspect = height / width;
var maxAspect = maxHeight / maxWidth;
if (aspect > maxAspect) {
img.style.height = maxHeight + "px";
} else {
img.style.width = maxWidth + "px";
}
}
}
You can see it in action here: http://jsfiddle.net/jfriend00/BeJg4/.
In the function assigned to onload:
> document.images[document.images.length-1].onload =
> resize_image_height_weight("i",150,150);
you are assigning the result of calling resize_image_height_weight which throws an error in IE. Set it to a function instead:
document.images[document.images.length-1].onload = function() {
resize_image_height_weight("i",150,150);
};

Categories

Resources