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

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/*">

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

"Load-Image" Javascript resize image before upload

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?!

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

Firefox addon uploading canvas contents to imgur

I am writing an addon in firefox that automatically sends the contents of a canvas to imgur. I have already built a similar extension in chrome, where it works as expected, so I know that the usage of imgurs API is correct. When I use the same approach in the Firefox addon, I always get this response:
{
"data": {
"error": "Image format not supported, or image is corrupt.",
"request": "/3/upload",
"method": "POST"
},
"success": false,
"status": 400
}
This is what I use to extract the image data and send it to the imgur API:
Request({
url: 'https://api.imgur.com/3/upload',
contentType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();
and this is used to get a selection from a canvas and get the dataurl of that selection:
function getImageSelection(type) {
//Create copy of cropped image
var mainImageContext = mainImage.getContext('2d');
var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);
var newCanvas = tabDocument.createElement("canvas");
newCanvas.width = selection.w;
newCanvas.height = selection.h;
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
return mainImage.toDataURL(type)
}
I have tried everything: using the dataurl from the original canvas (mainImage), getting the dataUrl without any type, this: .replace(/^data:image\/(png|jpg);base64,/, "");
But imgur keeps complaining about bad format.
In the end, it turned out that the usage of the Request module of the Firefox addon SDK was wrong.
Instead of using contentType to provide the type of the content (like in jquery/ajax), you have to use dataType. See below:
Request({
url: 'https://api.imgur.com/3/upload',
dataType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg', true)
},
onComplete: function (response) {
response = JSON.parse(response.text);
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();

Detect bad vimeo url with Jquery and Ajax

I'm experimenting with a site that generates random vimeo urls and plays them full screen with javascript. The site has a vhs appearance and is navigated with the arrow keys. (up arrow to "play" a vid, down to "pause").
VHS
I have the player working but am having difficulty detecting 404 and permission errors. I'm using ajax, json, and referenced this helpful thread. This thread as well.
Currently, I get my "Bad ID" alert when a valid url is generated and nothing when a bad url is generated. I would ideally like to re-generate video IDs until successful so users would never see a 404 or be asked for a password. Here is the meat of my code:
// if up arrow is pushed, show play div and hide others
if(e.which == 38) {
//generate video id and url
var video_id = Math.floor((Math.random()*10000000)+1)
var url ="https://vimeo.com/" + video_id;
var video_json = 'http://vimeo.com/api/v2/video/' + video_id + '.json';
//detect 404 with ajax
$.ajax({
type: 'GET',
url: video_json,
data: {format: 'jsonp'},
dataType: 'jsonp',
crossDomain: true,
success: function(resp) {
if (resp["id"]) {
alert ('good ID');
}
else {
alert ('bad ID');
//re-generate video_id until good
}
},
});
console.log(url);
console.log(video_json);
//play video with okvideo
$(function(){
$.okvideo({ source: url,
volume: 100,
loop: true,
hd:true,
adproof: true,
annotations: false,
// disablekeyControl: true,
onFinished: function() { console.log('finished') },
unstarted: function() { console.log('unstarted') },
onReady: function() { console.log('onready') },
onPlay: function() { console.log('onplay') },
onPause: function() { console.log('pause') },
buffering: function() { console.log('buffering') },
cued: function() { console.log('cued') },
});
});
Does anyone have suggestions? I understand this is a kind of hacky way to do accomplish this; there are obviously same-origin barriers at play and I'm open to using the API if this is method is a dead-end.
Thanks in advance!

Categories