Summernote rich text editor-restrict image above particular height and width - javascript

When I upload image in editor, I am able to find it's size.
But I want it's height and width to restrict for height and width above particular limit.
Below is result which I'm getting when I upload image.
See image to image upload result
For size restriction it's working as below-
onImageUpload(images, insertImage) {
if (images[0].size <= 100000) {
for (let i = 0; i < images.length; i++) {
const reader = new FileReader();
reader.onloadend = () => {
insertImage(reader.result);
};
reader.readAsDataURL(images[i]);
}
} else {
alert('Image not saved, max allowed image size is 100kb');
}
};

What editor are you using? UEditor is a very good rich-text editor.

onImageUpload(images, insertImage) {
console.log('onImageUpload', images);
if (images[0].size <= 100000) {
for (let i = 0; i < images.length; i++) {
const reader = new FileReader();
reader.onloadend = () => {
var i = new Image();
i.src = reader.result;
i.onload = function () {
if (i.width <= 200 && i.height <= 200) {
insertImage(reader.result);
} else {
cogoToast.warn('Image not saved, image width and height should be less than 200*200');
}
};
};
reader.readAsDataURL(images[i]);
}
} else {
cogoToast.warn('Image not saved, max allowed image size is 100kb');
}
};
It will work in this way.Thanks!

Related

description preview of uploaded images

I would like to add to the preview of uploaded images before uploading to the server the option to add a description of the image, which will be saved in the database, below the script displaying images and a preview image. Is anyone able to help me ?
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#chooseFile').on('change', function() {
multiImgPreview(this, 'div.imgGallery');
});
});
enter image description here

Image.width gives 0

I'm using a function to Validate the size of an uploaded image. That works fine, now I also want to check if the image is wider than certain pixels (like 1280 pixels). But the var width still gives zero. I already tried to use outerwith, innerwidth and file.files[0].width;
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
var NewFilze = FileSize.toFixed(2);
var height = file.height;
var width = file.width;
if (FileSize > 13) {
alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
}else if(width < 1280){
alert("The width of your image (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
}else{
}
}
Thanks in advance
You need to convert the file into an image :
Here is an example of How to convert a file to img to get width and hight :
function getSize(file) {
const img = new Image();
var file = file.files[0];
var reader = new FileReader();
reader.addEventListener("load", function() {
img.src = reader.result;
}, false);
const promise = new Promise((resolve, reject) => {
img.onload = () => {
console.log(img.naturalWidth, img.naturalHeight);
resolve([img.naturalWidth, img.naturalHeight]);
};
});
if (file) {
reader.readAsDataURL(file);
}
return promise.then(res => [img.naturalWidth, img.naturalHeight]);
}
You can do some changements to make it work for your case. Good luck
Without being able to test this on my own I would suggest trying something like the following:
function ValidateSize(file) {
var FileSize = file.files[0].size / 1024 / 1024; // in MB
var NewFilze = FileSize.toFixed(2);
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (FileSize > 13) {
alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
}else if(width < 1280){
alert("The width of your image (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
}else{
}
}
I should note this is untested and dependent on your js running on some browser (ideally chrome or FF). If it is server side I think visibleman is linked the best answer.
Good luck and happy hacking!!
Credit where its due SO post where I got the image code

Javascript - if boolean true not working

So, i created the following function to check the file uploaded by user is
1) Image only
2) Size less than maxSize KBs
3) Dimensions less than maxWidth and maxHeight
All else is working fine except that the condition where I check dimensions. The value in dimensions is indeed the correct value but the condition if(dimensions) doesn't run even when dimensions=true.
Is there something I am doing wrong?
var maxThumbnailWidth = '1050';
var maxThumbnailHeight = '700';
var maxThumbnailSize = '60';
function imageFileChecks(file, type) // type here refers to either Image or Banner or Thumbnail
{
var maxSize;
var maxWidth;
var maxHeight;
var dimensions = false;
if (type == 'image') {
maxSize = maxImageSize;
maxWidth = maxImageWidth;
maxHeight = maxImageHeight;
}
if (type == 'banner') {
maxSize = maxBannerSize;
maxWidth = maxBannerWidth;
maxHeight = maxBannerHeight;
}
if (type == 'thumbnail') {
maxSize = maxThumbnailSize;
maxWidth = maxThumbnailWidth;
maxHeight = maxThumbnailHeight;
}
//First check file type.. Allow only images
if (file.type.match('image.*')) {
var size = (file.size / 1024).toFixed(0);
size = parseInt(size);
console.log('size is ' + size + ' and max size is ' + maxSize);
if (size <= maxSize) {
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 width sizes', sizes.width);
console.log('onload height sizes', sizes.height);
var width = parseInt(sizes.width);
var height = parseInt(sizes.height);
if (width <= maxWidth && height <= maxHeight) {
dimensions = true;
console.log('dimensions = ', dimensions);
}
}
var objectURL = URL.createObjectURL(file);
img.src = objectURL;
if (dimensions) {
alert('here in dimensions true');
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
imageURL = response.url;
alert('all went well and image uploaded!');
return imageURL;
})
})
} else {
return errorMsg = 'Image dimensions not correct!';
}
} else {
return errorMsg = 'Image size not correct!';
}
} else {
return errorMsg = 'Image Type not correct!';
}
}
<div class="form-group">
<label class="col-md-6 col-xs-12 control-label">Thumbnail</label>
<div class="col-md-6 col-xs-12">
<input type="file" id="thumbnail" class="file" required>
<br>
</div>
</div>
<script type="text/javascript">
document.getElementById('thumbnail').onchange = function() {
var file = document.getElementById('thumbnail').files[0];
if (!file) {
console.log("ji");
return;
}
var type = 'thumbnail';
var thumbnailURL = imageFileChecks(file, type);
}
</script>
This seems like an async issue -- your if(dimensions) statement is running before your img.onload function finishes, in which case dimensions would be equal to false when you get to that part in your code, despite the img.onload function and its logic executing correctly.
You could try nesting the if(dimensions) condition in the img.onload function.
You set your dimension property inside the img.onload callback function.
This will not be executed directly. Then you check the value directly below, which will not be set yet. This is the nature of JavaScript: async functions being queued up to run at some time (example when an image finished loading).
To solve your problem, you need to make the rest of your function execute after img load. This can be done with either callback functions or promises.
I would read up on the asynchronous behavior a bit. Sorry for not providing a link, but should be plenty out there!
#William is right.You can handle it like that
function loadImage(src,callback){
var img = new Image();
img.onload = function() {
if (callback) {
callback(img);
}
}
img.src = src;
}

Uploading image and displaying it small with javascript

So, I've got this working javascript and it loads an image that a user uploads to the HTML on the screen displaying it.
But, it displays the image without a max height or width so it moves buttons on the page to where they can't be seen or pressed. This includes the submit button if the image uploaded is big enough.
So, is there some way to make the 'uploaded' image display really small: like max 30px in height?
$(function(){
$('#user_avatar').change(function(e){
var files = event.target.files;
var image = files[0];
for (var i = files.length - 1; i >= 0; i--) {
var reader = new FileReader();
var file = files[i];
reader.onload = function(file) {
var img = new Image();
img.src = file.target.result;
$('#inputpic').attr('src', file.target.result);
}
reader.readAsDataURL(image);
};
});
});
I have tried adding:
theimage = getElementById('inputpic')
theimage.style.height='10px';
But this had no effect.
EDIT 1
html.slim that the JS talks to:
= image_tag('temp.png', id: "inputpic", class: 'tiny_image_display')
SCSS that I made:
.tiny-image-display {
max-height: 30px;
}
You can set this in CSS very easily:
#inputpic {
max-height: 30px;
}
$(function(){
$('#user_avatar').change(function(e){
var files = event.target.files;
var image = files[0];
for (var i = files.length - 1; i >= 0; i--) {
var reader = new FileReader();
var file = files[i];
reader.onload = function(file) {
var img = new Image();
img.src = file.target.result;
img.height = "30";
$('#inputpic').attr('src', file.target.result);
}
reader.readAsDataURL(image);
};
});
});

Canvas image parsing orientation not in right sequence

i've image uploader which using canvas and trying to get orientation using load-image.all.min.js is fine. but when i choose multiple image orientation parsing function saving data not one by one.
which means if i choose 1 image. it transferring data to 'upload_canvas.php?ori='+ori with correct ori variable.
but when i choose multiple image to upload example 3 images (with orientation 1, 1, 8)
it passing data to server upload_canvas.php?ori=8, upload_canvas.php?ori=8, upload_canvas.php?ori=8. only last ori variable.
maybe orientation parsing function already looped before uploading image data to server one by one.
how to transfer image with correct orientation to server?
below my using code.
document.querySelector('form input[type=file]').addEventListener('change', function(event){
// Read files
var files = event.target.files;
var ori = 1;
// Iterate through files
for (var i = 0; i < files.length; i++) {
// Ensure it's an image
if (files[i].type.match(/image.*/)) {
//Get image orienatation
loadImage.parseMetaData(files[i], function (data) {
if (data.exif) {
ori = data.exif.get('Orientation');
console.log("ori: "+ori);
} else {ori = 1;}
});
// Load image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
canvas.width = image.width;
canvas.height = image.height;
drawImageIOSFix(canvas.getContext('2d'),image, 0, 0, image.width, image.height, 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) {
//some code
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'upload_canvas.php?t=' + Math.random()+'&ori='+ori, true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
// Clear files
event.target.value = '';});
Your variable ori is a global variable, that is shared between all images. The code in the .onload functions aren't run immediately, but only after your for() loop has gone through all the images. At this point ori will contain the orientation of the last image.
To fix, move the variable and parseMetaData into the reader.onload function.
...
var reader = new FileReader();
reader.onload = function (readerEvent) {
var ori;
loadImage.parseMetaData(files[i], ...)
var image = new Image();
image.onload = function (imageEvent) {
...
Warning: Not tested!

Categories

Resources