Javascript file resizing generating bad base64 string - javascript

I've been trying to resize images client side (using HTML5) before upload. It resizes it and sends through a base64 string, but it seems to be broken. The base64 string has spaces and line breaks and weird things, even if I take them out, it seems to still be broken.
This is my HTML:
<div class="form-group">
<canvas id="canvas"></canvas>
<label for="fileToUpload">Select Files to Upload</label>
<input type="file" id="FileUpload1" name="FileUpload1" />
<output id="filesInfo"></output>
</div>
And of course my javascript:
<script type="text/javascript">
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('FileUpload1').onchange = function () {
var files = document.getElementById('FileUpload1').files;
for (var i = 0; i < files.length; i++) {
resizeAndUpload(files[i]);
}
};
} else {
alert('The File APIs are not fully supported in this browser.');
}
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function () {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function () {
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.getElementById('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (ev) {
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'Upload', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(dataURL);
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
</script>
The dataURL variable, that's what contains the bad base64 string.

Here is your problem:
Base 64 encoded string includes characters like / and + , which as you can imagine have special significance if the request content type is said to be application/x-www-form-urlencoded. So, with your current code, + sign gets decoded as a space, and combinations like \n get interpreted as control characters such as line feed, new line etc.
All you have to do is encode dataURL to make sure it is safe for use as a parameter value. This is as simple as using the encodeURIComponent method.
i.e. var data = 'image=' + encodeURIComponent(dataURL);
Hope this helps.

Related

Multiple image resize with FileReader before php upload

I have a fine working multi-upload script in php (and a bit javascript).
The problem is, that users takes pictures directly from camera and so the image size is to large and mobile bandwith is small.
So i searched a solution to resize the image client-side and found some posts related FileReader and canvas.
My problem is how to upload the "result" of filereader with my php upload script.
That is what i have:
HTML:
<input id="fileupload" type="file" name="images[]" multiple/>
Javascript to dynamic add upload fields and preview uploads:
var abc = 0;
$(document).ready(function() {
$('#add-file-field').click(function() {
$("#newrow").append("<div class='col-sm-4'><div id='newrow' class='card'><div class='card-body'><input id='fileupload' type='file' name='images[]' multiple/></div></div></div>");
});
$('body').on('change', '#fileupload', function(){
if (this.files && this.files[0]) {
abc += 1;
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='card-img-top abcd'><img id='previewimg" + abc + "' src='' style='width:100%; height:100%;'/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
And the Php script:
$lastpositionid = $_SESSION['lastpositionid'];
$query = "INSERT INTO media (posid,orderid,name,image,created,tag,type) VALUES('$lastpositionid',$position->order_id,?,?,'$date','Vorher',?)";
$stmt = $con->prepare($query);
if(isset($_FILES['images'])){
$countfiles = count($_FILES['images']['name']);
$target_directory = "../uploads/". $position->order_id;
$file_upload_error_messages="";
for($i=0;$i<$countfiles;$i++){
if(!is_dir($target_directory)){
mkdir($target_directory, 0777, true);
}
$filename = $_FILES['images']['name'][$i];
$shafilename = sha1_file($_FILES['images']['tmp_name'][$i]) . "-" . date('d-m-Y-H-i-s') . "-" . basename($_FILES["images"]["name"][$i]);
$media->image = $filename[$i];
$file_size = $_FILES['images']['size'][$i];
$ext = end((explode(".", $filename)));
$valid_ext = array('jpg','JPG','jpeg','JPEG','png','PNG','gif','GIF','mov','MOV','mp4','MP4');
if(!empty($_FILES["images"]["tmp_name"][$i])){
if($file_size > 104857600){
$file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
$file_upload_error_messages.= "</div>";
}
if(in_array($ext, $valid_ext)){
}
else{
$file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
$file_upload_error_messages.= "</div>";
}
if(!empty($file_upload_error_messages)){
$file_upload_error_messages.= "<div class=\"alert alert-danger alert-dismissable\">";
$file_upload_error_messages.= "</div>";
}
if(empty($file_upload_error_messages)){
if(move_uploaded_file($_FILES['images']['tmp_name'][$i],$target_directory."/".$shafilename)){
echo "<div class=\"alert alert-success alert-dismissable\">";
echo "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>";
echo "</div>";
// Execute query
$stmt->execute(array($shafilename,'uploads/'.$position->order_id.'/'.$shafilename,$ext));
}
}
}
}
print_r($file_upload_error_messages);
}
Now i think i could use this script (or similar i found here):
function handleFiles()
{
var filesToUpload = document.getElementById('fileupload').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;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 400;
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");
document.getElementById('image').src = dataurl;
}
// Load files into file reader
reader.readAsDataURL(file);
}
The script of FileReader is clear to me except the part how to upload it again with php. Btw i´m more familiar with php than js and another problem is how to integrate this functionality in my existing script ...
I have no external upload script, it is all in the same php file.
Thanks.
You can't shrink an image on the client side and the upload it as a file, but you can shrink the image and then get a dataURI of the shurnken image and upload it as a string, then convert it back to an image on the server side.
var maxWidth = 100;
var maxHeight = 100;
document.getElementById("myfile").onchange = function() {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
var cnvs = document.createElement('canvas');
var rectRatio = img.width / img.height;
var boundsRatio = maxWidth / maxHeight;
var w, h;
if (rectRatio > boundsRatio) {
w = maxWidth;
h = img.height * (maxWidth / img.width);
} else {
w = img.width * (maxHeight / img.height);
h = maxHeight;
}
cnvs.width = w;
cnvs.height = h;
var ctx = cnvs.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
var uri = cnvs.toDataURL();
// Do something here to upload the smaller verion of the datauri
// for now i'm just putting it on the page though
document.body.innerHTML = '<img src="' + uri + '">';
};
img.src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
}
<input type=file id=myfile accept=".png">
Then on the PHP side you can save it as an actual image like this
$data = $_POST['mydatauri'];
$encodedData = str_replace(' ','+',substr($data,strpos($data,",")+1));
$decodedData = base64_decode($encodedData);
file_put_contents("myUploadImage.png", $decodedData);

Choose an image in browser, resize it and send it to server with JS, and let PHP save it on server

I'm working on this classical feature: choose a file in the browser ("Browse"), let JavaScript resize it (max width / height = 500 pixels) and upload it to server, and then let PHP save it to disk.
Here is what I currently have (based on this other question)
$("#fileupload").change(function(event) {
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'), max_size = 500, 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');
var resizedImage = dataURLToBlob(dataUrl);
$.ajax({type: "POST", url: "index.php", success: function(data, status) { }, data: { content: resizedImage, filename: ?? }});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
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});
}
<input id="fileupload" type="file">
The PHP part would be:
<?php
if (isset($_POST['content'])) file_put_contents($_POST['filename'], $_POST['content']);
?>
This currently doesn't work, how should I do the AJAX part to make it work (how to send the data + filename)? Should a FormData be used, if so why and how?
You need to use $_FILES array to retrieve the image info:
if (is_uploaded_file($_FILES['new_img']['tmp_name'])) {
$newimg = $_FILES['new_img']['name'];
move_uploaded_file($_FILES['new_img']['tmp_name'], "../images/{$newimg}");
}
file_put_contents is a function to write files. When you upload a file it is stored in a temp dir, so you can check with is_uploaded_file that it is uploaded with the $_FILES['new_img']['tmp_name'].
You can use it's original name with $_FILES['new_img']['name'] or rename it to prevent injections. Then you have to move the image to it's final location with move_uploaded_file.
I almost forgot the form:
<form action="yourpage.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="new_img" id="new_img">
<input type="submit" value="Upload Image" name="submit">
</form>

Can't limit number of files and save it to database, Image uploader Javascript and PHP

first of all Im really new with Javascript and lets tell you what i need.
I have this code to make an image uploader to resize it on client-side and works perfect, made by Joel Vardy. But I need to limint the number of images to upload by 10. I can't figured it out how to do it... also i can't find a way to host the image links on the Database via php
The HTML
<head>
<title>Upload Photos</title>
<link rel="stylesheet" href="./style.css" />
<head>
<body>
<h1>Upload Photos</h1>
<form>
<input type="file" accept="image/*" multiple />
<div class="photos">
</div>
</form>
<script src="./upload.js"></script>
</body>
The JS
document.querySelector('form input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
// Iterate through files
for (var i = 0; i < files.length; i++) {
// Ensure it's an image
if (files[i].type.match(/image.*/)) {
// Load image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Add elemnt to page
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
// Resize image
var canvas = document.createElement('canvas'),
max_size = 1200,
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);
// 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) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
// Start upload
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
// Clear files
event.target.value = '';
});
The PHP
$filename = md5(mt_rand()).'.jpg';
$data = file_get_contents('php://input');
$image = file_get_contents('data://'.substr($data, 5));
if ( ! file_put_contents('images/'.$filename, $image)) {
header('HTTP/1.1 503 Service Unavailable');
exit();
}
unset($data);
unset($image);
echo './images/'.$filename;
Any help will be appreciated, Thank you!
To limit the script to only work with max 10 files, do something like this:
for (var i = 0; i < files.length; i++) {
if (i < 11){
}
}
for the database, read about mysql and learn it.

flickr style image upload using html5 canvas

i am trying to make an image upload gallery using html5 canvas . I am trying to resize the images at the client side and show the preview . but when i upload multiple images with big size like 5mb each , the browser halts and sometimes crashes . I checked on flickr so their system instantly resize the uploaded images without any load to browser no matter how many pictures i upload . moreover my thumbnails when resized give the poor quality and whatever if i do something to make a make it better , the load on my browser shoots up . Here is my code for the images preview and resize
$(document).ready(function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('getfiles').onchange = function(){
var files = document.getElementById('getfiles').files;
for(var i = 0; i < files.length; i++) {
resizeAndUpload(files[i]);
}
};
} else {
alert('The File APIs are not fully supported in this browser.');
}
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function() {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function() {
var MAX_WIDTH = 220;
var MAX_HEIGHT = 120;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var newImgs = new Image();
newImgs.src = dataURL;
document.body.appendChild(newImgs);
}
}
reader.readAsDataURL(file);
}
For the "browser halts and sometimes crashes" part of your troubles...
Make sure you give the images time to load using .onload:
var newImgs=new Image();
newImgs.onload=function(){
document.body.appendChild(newImgs);
}
newImgs.src=dataURL;
And note that the .onload should be declared before .src
So, put .onload before .src on your tempImg also.
var tempImg = new Image();
tempImg.onload = function() {
...
}
tempImg.src = reader.result;
As far as the poor quality when up-sizing thumbnails, that's unavoidable.
You thumbnail only has a small pixel resolution and up-sizing will always create poor results.

Image resize before upload

I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the resize before upload option very effortless for the user. It seems my only options are a client side application that resizes the photos before uploading them via a web service, or a client side JavaScript hook on the upload operation that resizes the images. The second option is very tentative because I don't have a JavaScript image resizing library, and it will be difficult to get the JavaScript to run my current resize tool, ImageMagick.
I'm sure this is not too uncommon a scenario, and some suggestions or pointers to sites that do this will be appreciated.
In 2011, we can know do it with the File API, and canvas.
This works for now only in firefox and chrome.
Here is an example :
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);
There is multiple-technology-capable Plupload tool which declares that it can do resizing before upload, but I haven't tried it yet. I have also find a suitable answer in my question about binary image handling javascript libs.
You have several options:
Java
ActiveX (only on windows)
Silverlight
Flash
Flex
Google Gears (the most recent version is capable of resizing and drag and drop from your desktop)
I've done a lot of research looking for a similar solution to what you have described and there a lot of solutions out there that vary a lot in quality and flexibility.
My suggestion is find a solution which will do 80% of what you need and customize it to suit your needs.
I think you need Java or ActiveX for that. For example Thin Image Upload
What jao and russau say is true. The reason being is JavaScript does not have access to the local filesystem due to security reasons. If JavaScript could "see" your image files, it could see any file, and that is dangerous.
You need an application-level control to be able to do this, and that means Flash, Java or Active-X.
Unfortunately you won't be able to resize the images in Javascript. It is possible in Silverlight 2 tho.
If you want to buy something already done: Aurigma Image Uploader is pretty impressive - $USD250 for the ActiveX and Java versions. There's some demos on the site, I'm pretty sure facebook use the same control.
Here some modifications to feed tensorflow.js(soo fast with it!!) with resized and cropped image (256x256px), plus showing original image under cropped image, to see what is cut off.
$("#image-selector").change(function(){
var file = $("#image-selector").prop('files')[0];
var maxSize = 256; // well now its minsize
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var canvas2 = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
width *= maxSize / height;
height = maxSize;
}
} else {
if (height > maxSize) {
height *= maxSize / width;
width = maxSize;
}
}
if (width==height) { width = 256; height = 256; }
var posiw = 0;
var posih = 0;
if (width > height) {posiw = (width-height)/2; }
if (height > width) {posih = ((height - width) / 2);}
canvas.width = 256;
canvas.height = 256;
canvas2.width = width;
canvas2.height = height;
console.log('iw:'+image.width+' ih:'+image.height+' w:'+width+' h:'+height+' posiw:'+posiw+' posih:'+posih);
canvas.getContext('2d').drawImage(image, (-1)*posiw, (-1)*posih, width, height);
canvas2.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var dataUrl2 = canvas2.toDataURL('image/jpeg');
if ($("#selected-image").attr("src")) {
$("#imgspeicher").append('<div style="width:100%; border-radius: 5px; background-color: #eee; margin-top:10px;"><div style="position: relative; margin:10px auto;"><img id="selected-image6" src="'+$("#selected-image").attr("src")+'" style="margin: '+document.getElementById('selected-image').style.margin+';position: absolute; z-index: 999;" width="" height=""><img id="selected-image2" src="'+$("#selected-image2").attr("src")+'" style="margin: 10px; opacity: 0.4;"></div><div class="row" style="margin:10px auto; text-align: left;"> <ol>'+$("#prediction-list").html()+'</ol> </div></div>');
}
$("#selected-image").attr("src",dataUrl);
$("#selected-image").width(256);
$("#selected-image").height(256);
$("#selected-image").css('margin-top',posih+10+'px');
$("#selected-image").css('margin-left',posiw+10+'px');
$("#selected-image2").attr("src",dataUrl2);
$("#prediction-list").empty();
console.log("Image was loaded, resized and cropped");
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
let file = $("#image-selector").prop('files')[0];
reader.readAsDataURL(file);});});
Html implementation:
<input id ="image-selector" class="form-control border-0" type="file">
<div style="position: relative; margin:10px auto; width:100%;" id="imgnow">
<img id="selected-image" src="" style="margin: 10px; position: absolute; z-index: 999;">
<img id="selected-image2" src="" style="margin: 10px; opacity: 0.4;">
</div>
Also not resize to a maximum width/height, but to minimum. We get a 256x256px square image.
Pure JavaScript solution. My code resizes JPEG by bilinear interpolation, and it doesn't lose exif.
https://github.com/hMatoba/JavaScript-MinifyJpegAsync
function post(data) {
var req = new XMLHttpRequest();
req.open("POST", "/jpeg", false);
req.setRequestHeader('Content-Type', 'image/jpeg');
req.send(data.buffer);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++){
var reader = new FileReader();
reader.onloadend = function(e){
MinifyJpegAsync.minify(e.target.result, 1280, post);
};
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
You can resize the image in the client-side before uploading it using an image processing framework.
Below I used MarvinJ to create a runnable code based on the example in the following page:
"Processing images in client-side before uploading it to a server"
Basically I use the method Marvin.scale(...) to resize the image. Then, I upload the image as a blob (using the method image.toBlob()). The server answers back providing a URL of the received image.
/***********************************************
* GLOBAL VARS
**********************************************/
var image = new MarvinImage();
/***********************************************
* FILE CHOOSER AND UPLOAD
**********************************************/
$('#fileUpload').change(function (event) {
form = new FormData();
form.append('name', event.target.files[0].name);
reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = function(){
image.load(reader.result, imageLoaded);
};
});
function resizeAndSendToServer(){
$("#divServerResponse").html("uploading...");
$.ajax({
method: 'POST',
url: 'https://www.marvinj.org/backoffice/imageUpload.php',
data: form,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (resp) {
$("#divServerResponse").html("SERVER RESPONSE (NEW IMAGE):<br/><img src='"+resp+"' style='max-width:400px'></img>");
},
error: function (data) {
console.log("error:"+error);
console.log(data);
},
});
};
/***********************************************
* IMAGE MANIPULATION
**********************************************/
function imageLoaded(){
Marvin.scale(image.clone(), image, 120);
form.append("blob", image.toBlob());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<form id="form" action='/backoffice/imageUpload.php' style='margin:auto;' method='post' enctype='multipart/form-data'>
<input type='file' id='fileUpload' class='upload' name='userfile'/>
</form><br/>
<button type="button" onclick="resizeAndSendToServer()">Resize and Send to Server</button><br/><br/>
<div id="divServerResponse">
</div>

Categories