html5 canvas for multiple image uploads not uploading all images - javascript

I'm trying to resize multiple images through html5 filereader api on client side . It works fine for a single image but for multiple images , it usually uploads only one image and leave the rest and i cannot get what is the problem . Here is my code
function handleFileSelect(evt) {
var filesToUpload = evt.target.files;
for (var i = 0, f; f = filesToUpload[i]; i++) {
var img = new Image();
var reader = new FileReader();
reader.readAsDataURL(f);
reader.onload = function(e) {img.src = e.target.result;
};
img.onload = function (){ // also tried reader.onloaded here
canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 300; // 2048
var MAX_HEIGHT = 150; // 1600
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/jpeg");
var newImgs = new Image();
newImgs.src = dataurl;
document.body.appendChild(newImgs);
}
}

Related

Compress Image In Javascript using Telerik AsyncUpload

I have created a javascript function that compresses the JPEG image. It is working fine for JPEG files. But even user can upload xls,doc,pdf etc as well. So its breaking for any other files except JPG/JPEG. User can also upload other types of files as well. Only the JPG/JPEG needs to be compressed.
Else part is working perfectly fine. Need to fix the If part.
function OnClientFileSelected(radAsyncUpload, args) {
var old_uploadFile = radAsyncUpload._uploadModule._uploadFile;
var fileName = args.get_fileName();
var fileExtention = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
if (fileExtention.toLowerCase() != 'jpg' && fileExtention.toLowerCase() != 'jpeg') {
radAsyncUpload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
//return uploadFile;
var reader = new FileReader();
reader.readAsDataURL(uploadFile);
}
}
else {
radAsyncUpload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
var img = document.createElement("img");
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result
img.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var greaterDimension = 0;
var newPixelMultiplier = 1;
if (img.width > img.height)
greaterDimension = img.width;
else
greaterDimension = img.height;
if (greaterDimension > 1000) {
newPixelMultiplier = ((((greaterDimension - 1000) / 2) + 1000) / greaterDimension);
}
var MAX_WIDTH = img.width * newPixelMultiplier;
var MAX_HEIGHT = img.height * newPixelMultiplier;
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);
canvas.toBlob(function (blob) {
blob.lastModifiedDate = new Date();
blob.name = pair.file.name;
pair.file = blob;
old_uploadFile.call(this, pair)
}, 'image/jpeg', 0.6); //Set the Quality of Image...
}
}
reader.readAsDataURL(uploadFile);
}
}
}
It seems that the code for the resizing is from the following KB article: Preview uploaded image with RadAsyncUpload.
If that is the case, I can suggest that you that you keep the code as it is, or use it in the OnClientLoad event of the AsyncUpload control, as in your case it will be overridden on every file that is being selected.
Regarding your question in point, I can suggest you try to call the old_uploadFile as follows:
if (/*is not image condition here*/) {
old_uploadFile.call(radAsyncUpload, pair);
}
If the code from the KB is used, then it should be similar to this:
asyncupload._uploadModule._uploadFile = function (pair) {
var uploadFile = pair.file;
if (/*is not image condition here*/) {
old_uploadFile.call(this, pair);
return;
}
// rest of code for resizing images here
}

Resize image from input to upload

I've been struggled with this problem for couple hours. I want to resize an image from an input tag and then upload it to the server. Here is my attempt.
My input element:
<Input type="file" name="file" onChange={this.handleLoadAvatar} />
My handleLoadAvatar function:
handleLoadAvatar(e) {
var file = e.target.files[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = (e) => {
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;
var width = img.width; // GET STUCK HERE
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");
this.setState({previewSrc: dataurl});
}
I'm using ReactJS for my project. I got stuck at the line with the comment above where I can't get the image's width. I tried this solution at HTML5 Pre-resize images before uploading but this seems not to work for me. Can anybody point out what's wrong with my code and how to fix it? Thanks a bunch!
The problem is that you aren't waiting for the image to load before accessing its width and height.
As you are waiting for the reader, you should do the same for the img:
handleLoadAvatar(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = (e) => {
var img = document.createElement("img");
img.onload = () => {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 300;
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");
this.setState({previewSrc: dataurl});
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
}

Preview resized Image in Iframe

I have created a image select and resize (Client side) and upload to server. What I am asking for help is with image preview in iframe(resized) but cannot figure out. I will be only using Chrome desktop for this application. Qusetion is please help me with displaying resized image within my iframe here are my scripts below
HTML
<input type="file" input id="input" onchange="ClientSideResize()" name="Image" value="%%%img%%%"/>
HTML iframe
<img src="" id="image">
<iframe name="my_iframe" src="" id="my_iframe" style="visibility: hidden;"></iframe>
SCRIPT
<script>
function ClientSideResize(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
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;
img.onload = function () {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 400;
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);
dataurl = canvas.toDataURL("image/jpeg",100);
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "Sample"});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>
Giving you a few other tips along the way... filereader is not the preferred way. and the way you build your blob afterwards is no good, use canvas#toBlob directly instead.
function ClientSideResize () {
// var uniq = 'id' + Date.now() // never used
var filesToUpload = document.getElementById('input').files
var file = filesToUpload[0]
// Create an image
var img = new Image
img.onload = () => {
const MAX_WIDTH = 200
const MAX_HEIGHT = 400
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var width = img.width
var height = img.height
// figure out new width and hight while keeping proportionally
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
}
}
// set diminsion
canvas.width = width
canvas.height = height
// draw resized image
ctx.drawImage(img, 0, 0, width, height)
// get it as a blob
canvas.toBlob(blob => {
// Do something with blob
// let file = new File([blob], 'filename.png', {type: blob.type})
let iframe = document.querySelector('iframe')
iframe.contentWindow.postMessage(blob, '*')
}, 'image/jpeg', 100)
} // img.onload
img.src = URL.createObjectURL(file)
}
// on iframe
window.onmessage = event => {
console.log(event) // will contain your blob object
}

Javascript Image-Resize before upload

I'm trying to resize big/large images on client and upload the smaller image. This works perfectly with one or ten images. But i want to upload mybe 50+ images. This will work but it slows down my cpu and memory. The code for the resized images is this:
var MAX_WIDTH = 1920;
var MAX_HEIGHT = 1920;
var loaded = 0;
var URL = window.URL || window.webkitURL;
function loadImage(file) {
var mime = file.type;
var src = URL.createObjectURL(file);
var img = new Image();
img.onload = (function (image) {
return function () {
var newHeight = MAX_WIDTH;
var newWidth = MAX_HEIGHT;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(image, 0, 0, this.width, this.height, 0, 0, newWidth, newHeight);
URL.revokeObjectURL(this.src);
var dataURI = canvas.toDataURL(mime);
var blob = dataURLToBlob(dataURI);
imagesToUpload.push(blob);
loaded++;
if (loaded < checkedFiles.length) {
loadImage(checkedFiles[loaded]);
} else {
//DO UPLOAD
input.value = "";
}
}
})(img);
img.src = src;
image = null;
}
loadImage(checkedFiles[0]);
While resizing and uploading, i want to show a loading animation. And this anmiation is very slow.
I think the problem is while resizing the image on the canvas-object, but i have no idea to solve this issue.
The MAX-PICTURE-WITH is 1920px and the MAX-PICTURE-HEIGHT is 1920px.
It would be great if someone can give me a clue?

Get image dataUrl before file upload in Angularjs | ng-file-upload

I'm resizing the image before upload it to the server using HTML5 Canvas.
Also I use Angular's module ng-file-upload.
Stack on getting dataUrl of resized image. Console returns data:,
What could be the problem here?
HTML
<input type="file" ngf-select ng-model="files">
<img ngf-src="files[0]">
JS
$scope.upload = function (files) {
if (files && files.length==1) {
var file = files[0];
var img = document.createElement("img");
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.onload = function(e) {img.src = e.target.result};
reader.readAsDataURL(file);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 200;
var MAX_HEIGHT = 150;
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");
console.log( dataurl );
...
He had the same problem and solve it with:
$scope.upload = function (files) {
if (files && files.length==1) {
var file = files[0];
var URL = window.URL || window.webkitURL;
var srcTmp = URL.createObjectURL(file);
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = srcTmp;

Categories