Reputation: 57
function filePreview (input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#uploadForm + img').remove();
$('#uploadForm').after('<img src="'+e.target.result+'" width="840" height="600" />');
}
reader.readAsDataURL(input.files[0]);
}
}
$('#fileThumbnail').change(function() {
filePreview(this);
});
I am trying to preview the image but only accept images if they are of width:840px, height:600px no more and no less. and return a error to select an image of those exact dimensions
Upvotes: 0
Views: 1245
Reputation: 1
You can try to convert the file to Image element to get the width and height before applying.
I also add this line /(image\/)(jpeg|jpg|bmp|gif)/.test(input.files[0].type)
to check the file extension before converting (only images with extensions jpef
, jpg
, bmp
and gif
are accepted)
function filePreview (input) {
if(input.files && input.files[0] && /(image\/)(jpeg|jpg|bmp|gif)/.test(input.files[0].type)) {
var reader = new FileReader();
reader.onload = function(e) {
var image = new Image();
image.onload = function () {
// you can check the image width and height here
var width = this.width;
var height = this.height;
if (width === 840 && height === 600) {
// code goes here...
// $('#uploadForm + img').remove();
// $('#uploadForm').after(this);
}
$('body').append(this);
};
image.src = this.result;
}
reader.readAsDataURL(input.files[0]);
}
}
$('#fileThumbnail').change(function() {
filePreview(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="fileThumbnail" />
Upvotes: 2