Image corrupted when using Cropit and form submit - javascript

I was introduced to Cropit recently and find it really easy to use but I am stuck at one area. I am trying to use Cropit and form submit. I am following the demo provided by Cropit.
Javascript:
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
PHP:
$encoded = $base64_string;
$decoded = urldecode($encoded);
$image_name = explode(';', $decoded);
$image_name = explode(':', $image_name[0]);
$image = array_pop($image_name);
$ext = explode('/', $image);
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$str = random_string('alnum', 8);
$file = $str.'.'.$ext[1];
$data = $upload;
file_put_contents('assets/image_test/cropped/'.$file, $data);
It is able to output the file into my folder but the picture is just a blank screen with the dimension I set.
I have try to search the web but I couldn't find any solution to my problem.
Hope to get help from anyone who have encounter or know a solution.

Related

base64 string won't convert to image

I have the below base64 string generated from an app I'm testing out. It's supposed to generate an image but I can seem to get it to validate or display in HTML. I am trying to use PHP to decode and change to a JPG file but it seems the source of the base64 string may be the issue. Any thoughts?
I actually linked the file with the base64 in here since it's so many characters.
Thanks in advance!
PHP Code:
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
$source_type = "app";
if($pass == "Fan412") {
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../FOLDER_TO_IMAGES/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO TABLE_HERE (account, date, source_type, title, market, image) VALUES ('$account', '$date', '$source_type', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
}

base64 String is too long to send via Fetch HTTP API

I have a base64 image that is a very long character count and when I try to send it via Fetch POST API it gets cut off and makes the image unacceptable by my PHP file server-side. The base64 is the b64data variable in my below code. Any solutions or ideas would be appreciated!
function submitPhoto(){
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
The PHP:
<?php
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
//$source_type = "app";
if($pass == "Fan412") {
//Clean base64 String
//$image = str_replace(' ', '', $image);
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../MY_FOLDER/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO MY_TABLE (account, date, title, market, image) VALUES ('$account', '$date', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
} ?>
how about cut the base64_code into pieces then
post them before submit the whole form...
postData
{
'code': one piece_code,
'current_position': 1,
'full_pieces_count': a count you cut pieces
}
in php you can use redis to cache the base64_pieces with sorted_set piece1 piece2 ...( the score use the current_position you post)
after final pieces upload success...
combine them into pic to save then give js an img_url
then submit the whole form
btw: set the max length to post all the string...if it's too long...cut it and post them async/sync

canvas.toDataURL() From a live video feed capture then save to fileserver with reference in DB

I am working on a database where we need to have user form data and an image captured from a web cam then send the user data to the DB with a link to the photo on a file server. I am using the code found here http://davidwalsh.name/demo/camera.php (with added dataurl and base64 coding) for the image capture to canvas. I have searched for the past 2 weeks (unknown separate pieces of code changes and reversions) prior to posting here and have read a few people stating that a similar question has been asked about the Canvas.toDataURL() but it is just not working for me.
I am getting a file uploaded as a png but the file has a size of 0. I have no experience with other forms of coding (ruby/api/ajax/python) so I am not able to code with those. If those are mandatory then I will have to find another method (action script through Flash possibly) to make this work or abandon this until those scripts are learned.
Any info if this is even possible using PHP and mySQL would be helpful so I am not trying to create something that is not possible. The platofrm/delivery system will be an in house server on our intranet. currently testing on the web host server on windows computers running google chrome (also tested on firefox, opera and IE) Thanks in advance for taking the time to read through.
In my form.php
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var C = canvas.getContext('2d');
}
$('#canvas').submit()(function(event) {
// feel free to choose your event ;)
// just for example
// var OFFSET = $(this).offset();
// var x = event.pageX - OFFSET.left;
// var y = event.pageY - OFFSET.top;
// standard data to url
var imgdata = canvas.toDataURL('image/png');
// modify the dataUrl so the browser starts downloading it instead of just showing it
var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet- stream');
// give the link the values it needs
$('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);
});
In my addcontent.php
<?php
include("connectionInfo.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$name = $_POST['name'];
$phone = $_POST['phone'];
$duedate = $_POST['duedate'];
$employee = $_POST['employee'];
$address = $_POST['address'];
$email = $_POST['email'];
$estimate = $_POST['estimate'];
$dataURL = $_POST["canvas"];
//input file into images folder
$image = str_replace('data:image/png;base64,', '', $dataURL);
$image = str_replace(' ', '+', $dataURL);
$image = base64_decode($dataURL);
$filename = "$duedate$name.png";
file_put_contents('images/' . $filename, $dataURL);
// create path for image upload
$path = "images/" . $filename;
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
//show file location
echo "Stored in: ". $path;
//store file path in database
if(mysql_query("INSERT INTO JobBags (image) VALUES ('$path')")){
echo "Successfull!!";} else {
echo '---fail-sadface---';}
// put customer info into job bag database
$sql = "INSERT INTO JobBags (name, phone, duedate, employee, address, email, estimate, image)
VALUES ('$name', '$phone', '$duedate', '$employee', '$address', '$email', '$estimate', '$dataURL')";
//check if jobbag created correctly
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $mysqli . "<br>" . $conn->error;
}
// close connection to database
$conn->close();
?>

How to crop and upload photo using cropit jquery plugin with php

So I currently found this photo cropping plugin called cropit . Demos are here . So what I want to do is grab the cropped photo and upload the name of the photo to the mysql database and save it to a directory using php.
So far I have this :
HTML :
<form method="POST">
<div class="image-editor">
<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="hidden" name="image-data" class="hidden-image-data" />
<button type="submit">Submit</button>
</div>
</form>
jQUERY :
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
All I need help is with the php set up code because when I crop the photo and select submit, jquery returns the serialize code, and all this code that I'm usually not familiar with appears. Here is a few characters of the serialized code jquery returns:
image-data=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE...
1. Saving the base64 encoded image
<?php
//save your data into a variable - last part is the base64 encoded image
$encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$file = 'data.png';
//make sure you are the owner and have the rights to write content
file_put_contents($file, $data);
2. Getting the filename of base64 encoded image
$encoded = "data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhE";
$decoded = urldecode($encoded);
$exp = explode(';', $decoded);
$exp = explode(':', $exp[0]);
$image = array_pop($exp);
echo ($image);
I got Hosch Nok's answer to work by not decoding the encoded data.
Not calling:
$decoded = urldecode($encoded);
But working directly with the $encoded variable.

Generating a background image from a php file

I have to generate a background image from a php file and I can't get it to work properly. Here is my situation:
I have a javascript line where I call the php file like this:
document.body.style.background = 'url(http:/...../getBackground.php) no-repeat center center fixed';
In the getBackground.php file I had to generate the background image from a folder that contains a number (that can change) of images. I did it like this:
$dir = 'images/';
$arr = scandir($dir);
$images = array();
$pattern = '([^\s]+(\.(?i)(jpg|png|gif|bmp))$)';
foreach($arr as $file){if(preg_match($pattern, $file)){$images[] = $file;}} //get only the images from the folder
$count = count($images);
$i = mt_rand(0, $count - 1); // pick a random image
header("Content-type: image/png");
$photo = 'images/' . $images[$i];
$src_img = imagecreatefrompng($photo);
imagepng($src_img);
But something is wrong because I don't get the images displayed properly. Can anyone help? What am I missing?
Thanks a lot! Cheers!
Part of the problem is you are very specifically outputting png data, but allowing jpg, png, gif and bmp source files.
This should be a LOT faster and easier on the server. This does not recreate an image each time, it just passes through the existing image.
<?php
$dir = 'images';
$ext = 'jpg,gif,png'; // List the desired image extensions here, comma separated.
$images = glob($dir.'/*.{'.$ext.'}', GLOB_BRACE);
$random = $images[array_rand($images)];
$image_type = exif_imagetype($random);
header("Content-type: " . image_type_to_mime_type($image_type));
readfile($random);
?>

Categories

Resources