Is there any client side script can resize automatically the image uploaded in the input file by the user, and replace automatically the old image by the new image resized in the same input ..I want to do this to send this image to my php model after.. thanks in advance for your help.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<form action="model.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="do" value="submit"/>
</form>
</body>
</html>
<?php
$target_dir = "folder/";
$filename = $_FILES["image"]["name"];
$basename = basename($_FILES["image"]["name"]);
$target_file = $target_dir .$basename;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$tmp = $_FILES["image"]["tmp_name"];
if(move_uploaded_file($tmp,$target_file))
{
echo'done!';
}
?>
This is how i would have solved it...
// Used for creating a new FileList in a round-about way
function FileListItem(a) {
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError("expected argument to FileList is File or array of File objects")
for (b = (new ClipboardEvent("")).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
fileInput.onchange = async function change() {
const maxWidth = 320
const maxHeight = 240
const result = []
for (const file of this.files) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = await file.image()
// native alternetive way (don't take care of exif rotation)
// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap
// const img = await createImageBitmap(file)
// calculate new size
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height)
const width = img.width * ratio + .5 | 0
const height = img.height * ratio + .5 | 0
// resize the canvas to the new dimensions
canvas.width = width
canvas.height = height
// scale & draw the image onto the canvas
ctx.drawImage(img, 0, 0, width, height)
// just to preview
document.body.appendChild(canvas)
// Get the binary (aka blob)
const blob = await new Promise(rs => canvas.toBlob(rs, 1))
const resizedFile = new File([blob], file.name, file)
result.push(resizedFile)
}
const fileList = new FileListItem(result)
// temporary remove event listener since
// assigning a new filelist to the input
// will trigger a new change event...
fileInput.onchange = null
fileInput.files = fileList
fileInput.onchange = change
}
<!-- screw-filereader will take care of exif rotation for u -->
<script src="https://cdn.jsdelivr.net/npm/screw-filereader#1.4.3/index.min.js"></script>
<form action="https://httpbin.org/post" method="post" enctype="multipart/form-data">
<input type="file" id="fileInput" name="image" accept="image/*" />
<input type="submit" name="do" value="submit" />
</form>
PS. it won't resize in stackoverflow due to iframe being more sandboxed and secure, work in jsfiddle: https://jsfiddle.net/f2oungs3/3/
You could draw the image to a resized canvas via the FileReader API and then use canvas.toDataURL('image/png') to get the base64 image to send to the server.
Here is a simplified example of resizing an image to 320x240:
document.getElementById('example').addEventListener('change', function(e) {
var canvas = document.createElement('canvas')
var canvasContext = canvas.getContext('2d')
canvas.setAttribute("style", 'opacity:0;position:absolute;z-index:-1;top: -100000000;left:-1000000000;width:320px;height:240px;')
document.body.appendChild(canvas);
var img = new Image;
img.onload = function() {
canvasContext.drawImage(img, 0, 0, 320, 240);
var base64Image = canvas.toDataURL('image/png')
console.log(base64Image)
// Post to server
// sendImage(base64Image)
document.body.removeChild(canvas)
URL.revokeObjectURL(img.src)
}
img.src = URL.createObjectURL(e.target.files[0]);
})
function sendImage() {
var data = canvas.toDataURL('image/png');
var ajax = null;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'https://example/route', true);
ajax.setRequestHeader('Content-Type', 'application/octet-stream');
ajax.onreadystatechange = function() {
if (ajax.readyState === XMLHttpRequest.DONE) {
if (ajax.status === 200) {
// Success
} else {
// Fail
}
}
};
ajax.send(data);
}
<input id="example" type="file" />
And then on the server:
// or however you want to get the posted contents.
$png = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : file_get_contents("php://input");
if (strpos($png, 'data:image/png;base64,') === 0) {
$png = str_replace('data:image/png;base64,', '', $png);
$png = str_replace(' ', '+', $png);
$png = base64_decode($png);
}
file_put_contents($image_path, $png);
EDIT
The code now includes a way to upload the image to the server.
You could also use jQuery or the more modern fetch API to upload the image.
JsFiddle available here
Related
I was working on a project where a user can change his profile pic by using his webcam.
I successfully capture the image by webcam but I cannot append that capture image to my
form
here is my HTML code
<div class="form-group">
<label for="exampleInputFile">Profile Picture</label>
<div class="input-group">
<div class="custom-file">
<input type="file" id="photo" class="custom-file-input" name = "profile_pic" accept="image/png,image/jpg,image/jpeg">
<label class="custom-file-label" for="exampleInputFile">Choose Image</label>
</div>
</div>
</div>
<div class="camera">
<video id="video">Video stream not available.</video>
<button type="button" id="startbutton" class="btn btn-success" data-toggle="modal" data-
target="#modal-success">Take photo</button>
</div>
Here is my js code I follow this tutorial for help
<script>
(function() {
// The width and height of the captured photo. We will set the
// width to the value defined here, but the height will be
// calculated based on the aspect ratio of the input stream.
var width = 770; // We will scale the photo width to this
var height = 900; // This will be computed based on the input stream
// |streaming| indicates whether or not we're currently streaming
// video from the camera. Obviously, we start at false.
var streaming = false;
// The various HTML elements we need to configure or control. These
// will be set by the startup() function.
var video = null;
var canvas = null;
var photo = null;
var startbutton = null;
function startup() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
photo = document.getElementById('photo');
startbutton = document.getElementById('startbutton');
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function(stream) {
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
// Firefox currently has a bug where the height can't be read from
// the video, so we will make assumptions if this happens.
if (isNaN(height)) {
height = width / (4/3);
}
video.setAttribute('width', 340);
video.setAttribute('height', 300);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
startbutton.addEventListener('click', function(ev){
takepicture();
ev.preventDefault();
}, false);
clearphoto();
}
// Fill the photo with an indication that none has been
// captured.
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}
// Capture a photo by fetching the current contents of the video
// and drawing it into a canvas, then converting that to a PNG
// format data URL. By drawing it on an offscreen canvas and then
// drawing that to the screen, we can change its size and/or apply
// other changes before drawing it.
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/ ');
photo.setAttribute('src', data);
} else {
clearphoto();
}
}
// Set up our event listener to run the startup process
// once loading is complete.
window.addEventListener('load', startup, false);
})();
</script>
Now how can I put my capture image into <input type="file"> field, For Upload to server
Note: I don't want to use ajax for this.
1- Send base64 image as a string and then convert it to a file in the server side.
2- Convert a Base64 string into a Blob to upload it as a file to server.
I explain the second option:
First, Convert Base64 string to Blob with this function:
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data); // window.atob(b64Data)
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
Now, make your form (you can hidden it with CSS):
<form id="myAwesomeForm" method="post">
<input type="text" id="filename" name="filename" /> <!-- Filename -->
</form>
Then, append the image to form using FormData:
var form = document.getElementById("myAwesomeForm");
var ImageURL = photo; // 'photo' is your base64 image
// Split the base64 string in data and contentType
var block = ImageURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];// In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1];
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);
Finally you can send your formData using any method, For example:
var request = new XMLHttpRequest();
request.open("POST", "SERVER-URL");
request.send(formDataToUpload);
I hope this could help you ;)
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/jpeg');
var request = new XMLHttpRequest();
request.open("POST", 'SERVER_URL');
request.send(data);
} else {
clearphoto();
}
}
Check out this link for the full source code: https://colab.research.google.com/github/techwithanirudh/Automatic-Image-Captioning/blob/master/Capture_Img.ipynb
I am trying to resize an uploaded image and then upload the new image. My code runs without error and I could see the image was resized successfully but somehow the original image is being uploaded instead of the newly created image.
I am guessing e.target.files[0] = newimg; is not the right way to change the uploaded image file to the new image file. What should be the correct way?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ResizeImg(e)
{
const file = e.target.files[0];
const fileName = file.name;
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = event =>
{
const img = new Image();
img.src = event.target.result;
img.onload = () =>
{
const elem = document.createElement('canvas');
const ctx = elem.getContext('2d');
const maxWidth = 50;
const maxHeight = 50;
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
const width = img.width * ratio + .5 | 0;
const height = img.height * ratio + .5 | 0;
elem.width = width;
elem.height = height;
ctx.drawImage(img, 0, 0, width, height);
ctx.canvas.toBlob((blob) =>
{
const newimg = new File([blob], fileName, file);
e.target.files[0] = newimg;
});
}
};
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input name="infile" type="file" onchange="ResizeImg(this)">
<br><br><input type="submit" name="submit">
</form>
</body>
</html>
You are doing it technically correct BUT files from input are read only. So browser will not let you change those files. What you can do is create new form data and append all new images inside that and send upload it using fetch to send it async without refreshing page.
Found the answer at Resize image in the client side before upload. File input's filelist can be change with fileInput.files = fileList
I'm working on this classical feature: choose a file in the browser ("Browse"), let JavaScript resize it (max width / height = 500 pixels) and upload it to server, and then let PHP save it to disk.
Here is what I currently have (based on this other question)
$("#fileupload").change(function(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var canvas = document.createElement('canvas'), max_size = 500, width = image.width, height = image.height;
if (width > height) { if (width > max_size) { height *= max_size / width; width = max_size; } }
else { if (height > max_size) { width *= max_size / height; height = max_size; } }
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.ajax({type: "POST", url: "index.php", success: function(data, status) { }, data: { content: resizedImage, filename: ?? }});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) { var parts = dataURL.split(','); var contentType = parts[0].split(':')[1]; var raw = parts[1]; return new Blob([raw], {type: contentType}); }
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); }
return new Blob([uInt8Array], {type: contentType});
}
<input id="fileupload" type="file">
The PHP part would be:
<?php
if (isset($_POST['content'])) file_put_contents($_POST['filename'], $_POST['content']);
?>
This currently doesn't work, how should I do the AJAX part to make it work (how to send the data + filename)? Should a FormData be used, if so why and how?
You need to use $_FILES array to retrieve the image info:
if (is_uploaded_file($_FILES['new_img']['tmp_name'])) {
$newimg = $_FILES['new_img']['name'];
move_uploaded_file($_FILES['new_img']['tmp_name'], "../images/{$newimg}");
}
file_put_contents is a function to write files. When you upload a file it is stored in a temp dir, so you can check with is_uploaded_file that it is uploaded with the $_FILES['new_img']['tmp_name'].
You can use it's original name with $_FILES['new_img']['name'] or rename it to prevent injections. Then you have to move the image to it's final location with move_uploaded_file.
I almost forgot the form:
<form action="yourpage.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="new_img" id="new_img">
<input type="submit" value="Upload Image" name="submit">
</form>
first of all Im really new with Javascript and lets tell you what i need.
I have this code to make an image uploader to resize it on client-side and works perfect, made by Joel Vardy. But I need to limint the number of images to upload by 10. I can't figured it out how to do it... also i can't find a way to host the image links on the Database via php
The HTML
<head>
<title>Upload Photos</title>
<link rel="stylesheet" href="./style.css" />
<head>
<body>
<h1>Upload Photos</h1>
<form>
<input type="file" accept="image/*" multiple />
<div class="photos">
</div>
</form>
<script src="./upload.js"></script>
</body>
The JS
document.querySelector('form input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
// Iterate through files
for (var i = 0; i < files.length; i++) {
// Ensure it's an image
if (files[i].type.match(/image.*/)) {
// Load image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Add elemnt to page
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
// Resize image
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
// Upload image
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
// File uploaded / failed
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
// Start upload
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
// Clear files
event.target.value = '';
});
The PHP
$filename = md5(mt_rand()).'.jpg';
$data = file_get_contents('php://input');
$image = file_get_contents('data://'.substr($data, 5));
if ( ! file_put_contents('images/'.$filename, $image)) {
header('HTTP/1.1 503 Service Unavailable');
exit();
}
unset($data);
unset($image);
echo './images/'.$filename;
Any help will be appreciated, Thank you!
To limit the script to only work with max 10 files, do something like this:
for (var i = 0; i < files.length; i++) {
if (i < 11){
}
}
for the database, read about mysql and learn it.
How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?
Multiple images upload with info data preview
Using HTML5 and the File API
Example using URL API
The images sources will be a URL representing the Blob object
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">
const EL_browse = document.getElementById('browse');
const EL_preview = document.getElementById('preview');
const readImage = file => {
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);
const img = new Image();
img.addEventListener('load', () => {
EL_preview.appendChild(img);
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);
window.URL.revokeObjectURL(img.src); // Free some memory
});
img.src = window.URL.createObjectURL(file);
}
EL_browse.addEventListener('change', ev => {
EL_preview.innerHTML = ''; // Remove old images and data
const files = ev.target.files;
if (!files || !files[0]) return alert('File upload not supported');
[...files].forEach( readImage );
});
#preview img { max-height: 100px; }
<input id="browse" type="file" multiple>
<div id="preview"></div>
Example using FileReader API
In case you need images sources as long Base64 encoded data strings
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">
const EL_browse = document.getElementById('browse');
const EL_preview = document.getElementById('preview');
const readImage = file => {
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);
const reader = new FileReader();
reader.addEventListener('load', () => {
const img = new Image();
img.addEventListener('load', () => {
EL_preview.appendChild(img);
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);
});
img.src = reader.result;
});
reader.readAsDataURL(file);
};
EL_browse.addEventListener('change', ev => {
EL_preview.innerHTML = ''; // Clear Preview
const files = ev.target.files;
if (!files || !files[0]) return alert('File upload not supported');
[...files].forEach( readImage );
});
#preview img { max-height: 100px; }
<input id="browse" type="file" multiple>
<div id="preview"></div>
Demo
Not sure if it is what you want, but just simple example:
var input = document.getElementById('input');
input.addEventListener("change", function() {
var file = this.files[0];
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: this', this);
}
var objectURL = URL.createObjectURL(file);
console.log('change: file', file);
console.log('change: objectURL', objectURL);
img.src = objectURL;
});
If you can use the jQuery validation plugin you can do it like so:
Html:
<input type="file" name="photo" id="photoInput" />
JavaScript:
$.validator.addMethod('imagedim', function(value, element, param) {
var _URL = window.URL;
var img;
if ((element = this.files[0])) {
img = new Image();
img.onload = function () {
console.log("Width:" + this.width + " Height: " + this.height);//this will give you image width and height and you can easily validate here....
return this.width >= param
};
img.src = _URL.createObjectURL(element);
}
});
The function is passed as ab onload function.
The code is taken from here
Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.
If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.
HTML
<form class='frmUpload'>
<input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>
<div id='imgTwoForJPG'></div>
SCRIPT
<script>
window.picUpload = function(frmData) {
console.log("picUpload ran: " + frmData);
var allObjtProperties = '';
for (objProprty in frmData) {
console.log(objProprty + " : " + frmData[objProprty]);
allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};
document.getElementById('allImgProperties').innerHTML = allObjtProperties;
var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");
var img = new Image;
img.src = URL.createObjectURL(frmData);
console.log('img: ' + img);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var wdthHghtRatio = picHeight/picWidth;
console.log('wdthHghtRatio: ' + wdthHghtRatio);
if (Number(picWidth) > 400) {
var newHeight = Math.round(Number(400) * wdthHghtRatio);
} else {
return false;
};
document.getElementById('cnvsForFormat').height = newHeight;
console.log('width: 400 h: ' + newHeight);
//You must change the width and height settings in order to decrease the image size, but
//it needs to be proportional to the original dimensions.
console.log('This is BEFORE the DRAW IMAGE');
ctx.drawImage(img,0,0, 400, newHeight);
console.log('THIS IS AFTER THE DRAW IMAGE!');
//Even if original image is jpeg, getting data out of the canvas will default to png if not specified
var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
//The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};
</script>
Here is a jsFiddle:
jsFiddle Pick, display, get properties, and Re-size an image file
In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.
As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.
Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html
So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.
Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.
$('input').change(function() {
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function() {
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader.
$.ajax({url: img.src, async: false, success: function(result){
$("#result").html("READING IMAGE, PLEASE WAIT...")
$("#result").html("<img src='" + img.src + "' />");
console.log("Finished reading Image");
}});
};
img.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" capture="camera">
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)
A working jQuery validate example:
$(function () {
$('input[type=file]').on('change', function() {
var $el = $(this);
var files = this.files;
var image = new Image();
image.onload = function() {
$el
.attr('data-upload-width', this.naturalWidth)
.attr('data-upload-height', this.naturalHeight);
}
image.src = URL.createObjectURL(files[0]);
});
jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
var params = {
imageminwidth: options.params.imageminwidth.split(',')
};
options.rules['imageminwidth'] = params;
if (options.message) {
options.messages['imageminwidth'] = options.message;
}
});
jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
var $el = $(element);
if(!element.files && element.files[0]) return true;
return parseInt($el.attr('data-upload-width')) >= parseInt(param["imageminwidth"][0]);
});
} (jQuery));