Reputation: 149
How can I validate the image pixel? Below is my code, but for image type and size only.
<!DOCTYPE html>
<html>
<head>
<title>Image Validation</title>
<meta charset="utf-8">
<title>jQuery validation plug-in - comment form example</title>
<script src="lib/jquery.js"></script>
<script src="js/file-validator.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/cssval.css">
<body>
<fieldset>
<legend>Image</legend>
</p>
</li>
<li>Choose an image file:
<input type='file' class='demo' data-type='image' data-max-size='2mb' />
</li>
</fieldset>
</body> </html>
</head>
Upvotes: 1
Views: 4535
Reputation: 56
Use this inside you script
var _URL = window.URL || window.webkitURL;
function readURL(input,index) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#user_img_preview').attr('src', e.target.result); // You can show image preview before submit
}
reader.readAsDataURL(input.files[0]);
}
}
$("#user_img").change(function (e) {
// Check file is image or not
var file, img;
if ((file = this.files[0])) {
var fileName = this.files[0]['name'];
var idxDot = fileName.lastIndexOf(".") + 1;
var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
readURL(this,1);
img = new Image();
img.onload = function () {
if(this.width != 100 || this.height != 110) {
alert('Please upload proper image with exact size : 100 x 110');
}
};
img.src = _URL.createObjectURL(file);
}else{
alert('Only jpg/jpeg and png files are allowed!');
}
}
});
Upvotes: 1
Reputation: 24001
this is with jquery I thnk you have to preview img first whatever hidden or not and after preview use that code see THIS and Jsfiddle and after preview use that code
$(document).ready(function(){
var imgWidth = $('#target').width();
var imgHeight = $('#target').height();
if(imgWidth > 400 || imgHeight > 200){
alert('Your image is too big, it must be less than 200x400');
}
});
Upvotes: 2