Cropping an image on rails - javascript

I have the following data both in my js file or as a param in rails. Togther there is an image that is to be sent to server, what I want to achieve is to crop the image based on the data such as below. I am not allowed to use gems :) just using ruby/js code if I can manipulate the image already in js side. I am using cropper js which generated the output to me. What should I do to achieve cropping ?
{"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1}

Check out the fiddle: Link
This is the code you should be using, since your JSON is already formatted the same way Cropper takes its input:
//get the data from your rails framework and save it in a variable, below I just pasted the same data you put in your question
var data = {"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1};
//remember to change my-picture to the id of your img
$('#my-picture').cropper('setData', data);
//also make sure to bind this to your own button
$('#crop-button').click(function(e){
//this will transform the image into a blob, so you can submit it in form data
$(this).href = $('#my-picture').cropper("getCroppedCanvas").toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
//this is where you put your Rails path to upload
//it's going to be a POST, so you should know how to handle it
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
});

Related

Save an image from canvas to WordPress media library (or server)

I am trying to implement functionality that allows users to save a png generated on a canvas element into a WordPress media library, or at least on the server (this is an intermediate step to sharing the image on facebook, which requires a valid image URL).
So far, I've just been doing everything with JavaScript, and am trying to save the image to the server with an AJAX call. So far, this is my AJAX:
$(document).on('click','.facebook',function(e){
var image = document.getElementById("canvas");
var imageURL = image.toDataURL();
$.ajax({
type: "POST",
url: "http://myexample.com",
data: {
imgBase64: imageURL
}
}).done(function(o) {
console.log('saved');
});
I guess I'm also a little unsure as to what is supposed to go in my url....I tried using the path for the images in my actual media library, but got a "permission denied" error when I tried to execute this.
Can anyone help?
There should be admin ajax URL. you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
Then use it in your script like this:
$(document).on('click','.facebook',function(e){
var image = document.getElementById("canvas");
var imageURL = image.toDataURL();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
imgBase64: imageURL
}
}).done(function(o) {
console.log('saved');
});
I'm not sure if WordPress has a REST API to upload images, so here is another approach: You can create your custom endpoint with the following action register_rest_route
Inside the function you can handle the image upload, heres an example of how to create a custom REST endpoint (http://example.com/imageHandler/v1/upload with type POST).
add_action( 'rest_api_init', function () {
register_rest_route( '/imageHandler/v1', '/upload', array(
'methods' => 'POST',
'callback' => 'uploadImage',
) );
} );
function uploadImage($request) {
$base64Image = $request['imgBase64'];
}
Inside the uploadImage function you might want to try this solution for uploading base64 images: https://gist.github.com/tjhole/3ddfc6cbf6da01c7ce0f since WordPress alone can't handle base64 uploads.
After uploading you can return the image url by calling: wp_get_attachment_url

sending array of edited array of files(images) to php script

I have a form containing an input of type file that can accept multiple files(images) as shown below:
<input type="file" id="fileupload" name="fileupload[]" multiple />
Once a user selects an image or multiple images they are added dynamically to the website and also the user can remove one or all of them if he wants to.
Is there a way I can update which files are chosen from the input element to send to php script?
If not how can I send only images the user chooses? I mean I can put what the user chose in another array in JavaScript but how can I send them to php script?
Edited
In more details for example when the user chooses three image files there is JavaScript code i use that appends them into screen as images and the user is given the option to remove one or all of them by clicking on them. So my problem is if the user for example removed one of the images how can I send only the other two images into the php script?
I am not looking for complete code. I am just looking for a hint on how to accomplish it.
I've understood what you want.
Combine Ajax with formData to get that.
$(document).ready(function(){
$("form#data").submit(function(){
// create your filtred list of files from your file input
var data = {};
$.each($('#fileupload')[0].files, function(i, file) {
// Keep only the files that the user has selected
if ( i % 2 == 0){ // <--- CHANGE THIS
data['file-'+i] = file;
}
});
// create a FormData (to send files with AJAX)
var formData = new FormData();
for (var key in data) {
formData.append(key, data[key]);
}
// send that formData
php_script_url = "your_script.php"
$.ajax({
url: php_script_url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Don't forget to include jQuery before this script
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

Run PHP, wait; run JavaScript, wait; then submit form?

What I need to do:
I have an upload form with a file input and hidden text inputs. The user uploads an image, the image gets manipulated and then sent to remote server for processing which takes a few seconds, then the remote server sends the finalized images back to the home server where they are saved in a new folder. JavaScript needs to reach these new images to do further data processing on the newly saved images (which also takes a second). Only after JavaScript has done its thing and updated the form's input variables can the form be submitted.
Right now I've got all of the separate pieces working, but executing everything in one click has proven to be a challenge.
My code for uploading the images:
PHP:
if(isset($_POST['submit'])){
//do image manipulation and save new files using PHP
}
JS:
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
}
PHP again:
if(isset($_POST['input_variables'])){
//send these variables to SQL database
}
I know trying to use JavaScript to get the newly saved images isn't an ideal approach, but the framework that I'm using is only available in JavaScript. Is this even possible with one click?
You can do this:
In your HTML, add data-processed="false" to your form like this:
<form action="upload.php" method="post" name="q_data" data-processed="false" enctype="multipart/form-data">
In your jQuery call this to submit the images via ajax:
$("form[name='q_data']").submit(function(e) {
var $this = $(this);
var processed = $this.data('processed')
if (processed == false) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: formData ,
async: false,
success: function(msg) {
//alert(msg);
if (msg !== 'success') {
$this.data('processed', true)
furtherProcessing();
}
},
cache: false,
contentType: false,
processData: false
});
}
});
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
$("form[name='q_data']").submit();
}
In some-page.php do this:
if(isset($_POST['some-image-input-name'])){
//do image manipulation and save new files using PHP
return 'success'
}
However, if it were me, I'd have that first ajax call (that saves the images) simply return the urls for the saved images, then there is no need for a second ajax call to retrieve them which I assume is what you are doing now

How to upload a captured photo to REST interface using JSON - JQuery by PhoneGap (iPhone)?

My application asks from the user to capture an photo and then upload it to the server if the user is online. The code for the photo capture I took from PhoneGap API. How can I use the imgURL to upload it to the REST interface using Json and Jquery mobile?
The code I have up to now is:
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
Again, it is the same code taken from the PhoeGap API... I appreciate any help!...
Not sure if I understand your question correctly.
You should have your rest url and data structure (in JSON) the endpoint expects.
Once you have the base64 encoded string Use JSON library for packing JSON data and then send it to the service using
jquery.ajax().
Edited to include the post code
$.ajax({
type: 'POST',
url: yoururl,
data: jsondata,
success: success,
dataType: dataType
});
Content type will usually be
contentType: "application/json; charset=utf-8"
and datatype will be
dataType: 'json'

Save chart image with open flash chart2

I am using Open Flash Chart 2 to create some graphs. I want to be able to save an image of the graph, which OFC2 supplies some methods to accomplish this. I used the example on the OFC2 site to directly display the raw image data on the page, but that does not work in IE6, which most of our users are using (I know, I know).
I switched to using the OFC2 method, post_image to post the raw image data to the server. I use a Perl script to receive the image data, save it to a file, and I can view the image. The unfortunate part about using the post_image method is that ActionScript throws an error when saving the image:
Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Which apparently is a bug in Adobe - see this page. Because of this error, the post_image method does not complete successfully, so the javascript callback won't ever fire - I basically don't have a way to tell if the image was saved successfully.
So, I thought I would use the get_img_binary method of OFC2 to get the binary data of the image, and use jQuery to post the binary data to my Perl script.
I cannot figure out how to send the binary data correctly, or how to let my Perl script receive the binary data correctly, or both.
Here is my jQuery function:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
//contentType: 'application/octet-stream',
contentType: 'image/png',
//processData: false,
//data: { imgData: chartObj.get_img_binary() },
data: chartObj.get_img_binary(),
dataType: "text",
success: function(data) {
console.log( data );
}
});
You can see from some of my commented out lines that I have tried various contentTypes and other settings of the Ajax call.
The Ajax call is sending some data, but it doesn't appear to be binary. I think it is a base64 representation of the binary data.
Does anyone have any ideas on how to send binary data from javascript to the server?
The Perl script I have works fine for the post_image method, so I don't think the problem is there?
Thanks in advance!
I seem to have stumbled onto the solution.
Here is my ajax call:
var chartObj = $("#chart_object").get(0);
$.ajax({
type: "POST",
url: 'download_image.pl',
contentType: 'application/octet-stream',
processData: false,
data: imgData,
dataType: "text",
success: function(data) {
console.log( data );
}
});
And here is my Perl snippet to process/save the image:
use CGI qw(:standard);
use MIME::Base64;
...
my $img64 = param('POSTDATA');
my $img = decode_base64( $img64 );
...
#then print $img out to a file in binary mode
I had to decode the base64 representation of the PNG file, and then save it to a file.
i've got trouble too with using IE6 and OFC2 for saving image... So here are the scripts i use (javascript + PHP)
i know it's not very beautifull but jQuery doesn't want to work in a popup created via window.open('') on my IE6 so i decided to use a "old school method" to get it...
// javascript in the page displaying the flash chart
OFC = {};
OFC.jquery = {
name: "jQuery",
image: function(src) { return '<img src="data:image/png;base64,' + $('#'+src)[0].get_img_binary() + '" \/>'},
popup: function(src) {
var img_tag = OFC.jquery.image(src);
var img_win = window.open('', 'imagesave');
img_win.document.write('<html><head><title>imagesave<\/title><\/head><body>'+ img_tag + '<\/body><\/html>');
img_win.document.close();
},
popupie: function(src) {
var img_data = "image/png;base64,"+$("#"+src)[0].get_img_binary();
var img_win = window.open('', 'imagesave');
with(img_win.document) {
write('<html>');
write('<head>');
write('<title>imagesave<\/title>');
write('<\/head>');
write('<body onload="document.forms[0].submit()">');
write('<form action="\/ofc\/base64post.php" method="post">');
write('<input type="hidden" name="d" id="data" value="'+img_data+'" \/>');
write('<\/form>');
write('<div><img src="\/ofc\/ajax-loader.gif" border="0" alt="" \/><\/div>');
write('<div style="font-family: Verdana;">Please wait<br \/>After you can save the image<\/div>');
write('<\/body>');
write('<\/html>');
}
img_win.document.close();
}
}
function save_image() { // this function is automatically called
if ($.browser.msie)
OFC.jquery.popupie("my_chart"); // only for IE navigators
else
OFC.jquery.popup("my_chart"); // for the others
}
so, when we use the save_image() function (which is automaticaly called when you right clic dans select "Save Image Locally" on the flahs chart)
the image of the chart is tranfered to the popup and the data (base64 binary image) are posted to a php script /ofc/base64post.php that rander the picture :
<?php
// base64post.php
$data = split(';', $_POST['d']);
$type = $data[0];
$data64 = split(',', $data[1]);
$pic = base64_decode($data64[1]);
header("Content-type: $type");
echo $pic;
?>
hope that help someone !

Categories

Resources