image preview before uploading -IOS - javascript

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>

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;

When I try to upload an image as canvas through FileReader, I need to upload twice, else it is a blank image that gets posted

I'm trying to upload an image with FileReader() and convert it to base64. This only works when after I upload the image twice, otherwise, a blank canvas/image gets posted instead.
This is my input:
<input type="file" id="file" class="file"/><canvas id="canvas"></canvas>
This is the FileReader():
var file = document.querySelector('input[type=file]').files[0];
var fr = new FileReader();
fr.onload = createImage; // onload fires after reading is complete
fr.readAsDataURL(file); // begin reading
function createImage() {
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
}
function imageLoaded() {
var canvas = document.getElementById("canvas")
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
}
var img64 = canvas.toDataURL().split(",")[1];
var params = {
"media_data": img64
};

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

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: Setting Image to Canvas doesn't work right

I'm basically trying to get the selected image file from a input dialog and set it to a canvas that's in my HTML. However, the image gets cropped and only a portion of the image is shown.
Javascript:
function onSS1Change(file) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function () {
ctx.drawImage(img, 20, 20);
}
img.src = URL.createObjectURL(file.target.files[0]);
}
HTML:
<input id="ss1-inputdiag" type="file" onchange="onSS1Change(event)" />
Fiddle: http://jsfiddle.net/tdy9tqfh/
I need to get the original height and width
What am I doing wrong?
jsFiddle : http://jsfiddle.net/CanvasCode/tdy9tqfh/2/
Just update the canvas height and width to fit the image, also you were drawing your image at position x 20 and y 20 so all your images will be slightly cut off at the right side and bottom.
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
var img = new Image;
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0,0);
alert('the image is drawn');
}
}

Categories

Resources