Reputation: 2775
In my controller i receive from form data like this:
"output":{"width":500,"height":500,"image":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQFAH/9k=..."},"actions":{"crop":{"x":97,"y":0,"height":500,"width":500},"size":null}}[
Can I create image file from this data?
upd 1. Decode the json - ok, pull out the image data - ok, decode the base64 - ok, but when I try write to disk then I got error: NotReadableException in Decoder.php line 96: Unable to init from given binary data.
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$image = base64_decode($file);
$png_url = "user-".time().".png";
$path = "/public/".$png_url;
Image::make($image)->save($path);
upd 2. Solved with file_put_contents function.
Upvotes: 2
Views: 2751
Reputation: 2775
This is working:
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$png_url = "user-".time().".png";
$path = "uploads/".$png_url;
$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
file_put_contents($path, $image);
Upvotes: 1
Reputation: 5509
here is how you can save image from a json data:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
echo imagejpeg($im , base_path() . DIRECTORY_SEPARATOR . "sth.jpeg") ;
}
else {
echo 'An error occurred.';
}
Upvotes: 2