"Load-Image" Javascript resize image before upload - javascript

I'm developing a small function for an image-upload. This image-upload resizes selected pictures on the client and upload the resized image.
This works, but the browser will hang a lot between "resizes-functionality".
This is my code:
function manageImage(file) {
if (!file) return;
var mime = file.type;
var src = URL.createObjectURL(file);
loadImage.parseMetaData(file, function (data) {
var options = { maxWidth: 1920, maxHeight: 1920, canvas: true };
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file,
function (img, test) {
loaded++;
var formData = new FormData();
formData.append("image", dataURI);
$.ajax({
url: "/URL",
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
type: "POST",
success: function (resp) {
}
}).error(function () {
}).done(function () {
if (loaded < checkedFiles.length) {
manageImage(files[loaded]);
} else {
//FINISHED
}
});
},
options);
});
}
manageImage(files[0]);
This funcition is recursive, because i had some problems with the iteration (browser-hang, memory and cpu-usage).
Additionally, i'm using this library for EXIF-Data and correct orientation on mobile phones:
https://github.com/blueimp/JavaScript-Load-Image
With one or two selected pictures (e.g. 7MB) it works perfect, but i want to upload maybe 50 pictures.
It would be great if someone can give me a clue?!

Related

How to get the base64 image from TUI Image Editor?

Hello im new'ish in using and editing api's and im a bit stumped on TUI's Image Editor.
I'm trying to get the image data as a variable so that I can upload it separately to a website instead of just downloading it to the computer.
I am using this person's version of tui. I tried other methods as well but they didn't quite worked out for me.
const imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme, // or whiteTheme
initMenu: 'filter',
menuBarPosition: 'bottom',
},
cssMaxWidth: 700,
cssMaxHeight: 500,
usageStatistics: false,
});
window.onresize = function () {
imageEditor.ui.resizeEditor();
}
document.querySelector('#downloadButton').addEventListener('click', () => {
const myImage = instance.toDataURL();
document.getElementById("url").innerHTML = myImage;
});
</script>
<p id="url">Test</p>
Tried to change the code by using other guides but now it shows this error
Changed code
var imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme,
initMenu: 'filter',
menuBarPosition: 'left'
},
cssMaxWidth: 700,
cssMaxHeight: 1000,
usageStatistics: false
});
window.onresize = function() {
imageEditor.ui.resizeEditor();
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
</script>
Added in some false statements so that the object form can be sent.
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
contentType: false, //added
processData: false, //added
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});

Croppie.js is also selecting Videos while browsing files for Images

I am using Croppie.js for cropping and uploading images on my site. However, I found that while browsing for images, it also shows video and other format files and is even selecting it. I searched the documentation for the solution but could not find it. It does says in documentation about the formats supporting jpeg and png but that is only at the result. I did not find a way to restrict displaying video files. Any help would be appreciated.
Code:
// Croppie
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 300,
height: 300,
type: 'circle' //square
},
boundary: {
width: 325,
height: 325
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
// console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.btn-upload-image').on('click', function (ev) {
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
var imgval = $('#image').val();
var dataString = {
image: img,
imgval: imgval
};
$.ajax({
type: "POST",
dataType : "json",
url: "processes/avatar.php",
data: dataString,
beforeSend: function(){
$('.message').hide();
$(".btn-upload-image").html('Please wait...');
},
success: function (json) {
$(".message").html(json.msg).fadeIn();
$('#preview-image').attr('src', json.preview);
$(".btn-upload-image").html('Upload');
}
});
});
});
Oh I got the solution! Holy crap, just within a minute after posting the question. No worries, the answer will help future searchers.
HTML5 supports accept attribute to define what type of file should be accepted. I simply put the in the code this way:
<input type="file" id="image" accept="image/*">

Ajax method working twice in a button click

The file upload function working on the Upload button click.The function
$("#fuPDFAdd").change(function () {})
file upload change is working two time when click the 'btnUploadAdd' button.
How can avoid this
<div id="divUploadFileAdd">
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input id="fuPDFAdd" name="file" type="file" style = "display:none;"/>
<button class="" id="btnUploadAdd" type="button" onclick="test()">Upload</button>
<label id="txtuploadedMsgAdd"> </label>
</form>
</div>
$(document).ready(function () {
$("#fuPDFAdd").change(function () {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
grdStaffAddition.PerformCallback({ transStatus: "New" });
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
}
else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
});
});
function test() {
$("#fuPDFAdd").click();
}
Something like this will work, I did wrap the file upload code to a separate function there, and make it to call this new function from your event listeners.
function uploadTheFile() {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function(data) {
grdStaffAddition.PerformCallback({
transStatus: "New"
});
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
} else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
}
$("#fuPDFAdd").change(function() {
uploadTheFile();
});
function test() {
uploadTheFile();
}

Send Cropped image to database ajax On client and PHP on server

I am trying to upload a image to Database using Javascript on client and PHP on server.
first image is selected from the gallery.
after zooming and cropping the image is passed to database
The Problem is when iam trying to submit the cropped image value is not passed to the php the actual uploaded input "File" Value is Being Passed, but i need the cropped areas value to be passed to PHP.
For testing purpose if all the js are required i can provide it.
Js: This Crops the image
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
HTML:
<form id="uploadForm" class="image-editor">
<input type="file" class="cropit-image-input">
<!-- .cropit-image-preview-container is needed for background image to work -->
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="submit" class="export">Export</input >
</form>
Ajax: ajax sends the data to php
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
PHP:
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$mysl = mysqli_connect("localhost", "root", "root","test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "UPDATE output_images SET imageType ='{$imageProperties['mime']}',imageData= '{$imgData}' WHERE imageId='16'";
$current_id = mysqli_query($mysl,
$sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());;
if(isset($current_id)) {
echo "done";
}
}
}
First, take a look at this: Can I pass image form data to a PHP function for upload?
I think the issue is here: var imageData = $('.image-editor').cropit('export');. Since this new image is never a part of the form, there is no way to pass it via AJAX.
In your JS/JQuery, I would advise:
var imageData = '';
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
fd.append( imageData, file );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
EDIT
In your example, you never defined a name or id attribute for your input, so there would be no way for PHP to index the $_FILES global. Could try $_FILES[0]. I would advise assigning that in your form or when you post it.
You can adjust the myFormData.append(name, file, filename);. So it would be:
fd.append('crop-image', imageData, 'crop-image.jpg');
Then in PHP, you call it using $_FILES['crop-image']. If you want to pass the file name from the form:
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
var origFileName = $("input[type='file']").val();
var startIndex = (origFileName.indexOf('\\') >= 0 ? origFileName.lastIndexOf('\\') : origFileName.lastIndexOf('/'));
var filename = origFileName.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0){
filename = filename.substring(1);
}
var cropFileName = "crop-" + filename;
fd.append('crop-image' imageData, cropFileName );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});

uploading file using JavaScript - how to get more frequent onprogress events

I'm using jQuery to upload a photo, and have attached a listener for onprogress events. However even when uploading photos that are a few megabytes, the only onprogress event that gets fired is when its at 100%. I've seen other sites like dropbox and facebook show a much more fluid progress bar. How can I get more frequent updates on the upload progress?
Sample upload Code:
var file = $photoFile.get(0).files[0];
var fileBlob = file && file.slice();
var formData = new FormData();
var title = $photoTitle.val();
formData.append('file', fileBlob);
formData.append('title', title);
$.ajax({
url: '/api/v1/photo/submit',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
xhrFields: {
onprogress: function(ev) {
console.info('upload progress', ev);
if (ev.lengthComputable) {
var percentUploaded = Math.floor(ev.loaded * 100 / ev.total);
console.info('Uploaded '+percentUploaded+'%');
// update UI to reflect percentUploaded
} else {
console.info('Uploaded '+ev.loaded+' bytes');
// update UI to reflect bytes uploaded
}
}
}
}).done(function(response) {
// do stuff
}).fail(function() {
// handle error
});
I was able to do this borrowing code from this stackoverflow question.
The key mistake I was making was relying on the onprogress within the xhrFields property of the call to $.ajax. Instead, to get more frequent progress updates I passed a custom XMLHttpRequest using the xhr property:
$.ajax({
url: '/api/v1/photo/submit',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress',function(ev) {
if (ev.lengthComputable) {
var percentUploaded = Math.floor(ev.loaded * 100 / ev.total);
console.info('Uploaded '+percentUploaded+'%');
// update UI to reflect percentUploaded
} else {
console.info('Uploaded '+ev.loaded+' bytes');
// update UI to reflect bytes uploaded
}
}, false);
}
return myXhr;
}
}).done(function(response) {
// do stuff
}).fail(function() {
// handle error
});
Warning: This leverages newer web technologies and doesn't work with older browsers, especially IE.

Categories