Preview resized Image in Iframe - javascript

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
}

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
}

javascript resize and preview multiple image before upload

I'm newbie in JS and React. I am using React and I have multiple file input in a form, I wish if the user select image the images should be resized and previewed before user click upload. Now the resizing, previewing and uploading are all fine, the problem is when I change a file input, the other file inputs preview and upload are all changed synchronously! any help will be appreciated.
This is the code:
render():
render(){
return(
...
<label>Image1
<input type="file" id="img1" on Change={this.handleChange} />
</label>
<br/>
<img id="img1_preview" src="" height="100" />
<label>Image2
<input type="file" id="img2" on Change={this.handleChange} />
</label>
<img id="img2_preview" src="" height="100" />
...
)
}
function():
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
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');
var max_size = 800; /* max size */
var 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');
/* Utility function to convert a canvas to a BLOB */
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});
}
/* End Utility function to convert a canvas to a BLOB */
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
$(document).on("imageResized",function(event1){
if (event1.blob && event1.url) {
var blob = event1.blob, url = event1.url;
# set state, later will be submit to server
this.setState({[field]:blob});
/* preview */
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = url;
}, false);
reader1.readAsDataURL(blob);
/* end preview */
}
})
}
the page:
the page image
thanks #Kaiido, according to his advise, the problem has been solved(although I don't know the exact reason).
this is the working code:
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
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');
var max_size = 800; /* max size */
var 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');
/* changed code */
canvas.toBlob(function(blob){
this.setState({[field]:blob});
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = dataUrl;
}, false);
reader1.readAsDataURL(blob);
});
/* end changed */
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}

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);
}

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;

html5 canvas for multiple image uploads not uploading all images

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);
}
}

Categories