Saving base64 image to server not working in PHP - php

Iam getting base64 image in a json like below format
{
"profilepic":"iVBORw0KGgoAAAANSUhEUgAAAPAAAABGCAYAAADyxhn6AAAMYml..."
}
I have a PHP code like below, where i decode this base64 image and save it in server, i tried to run the code and am not able to see the image in particular folder location.
Can anyone help me to identify the problem here?
<?php
header("Access-Control-Allow-Origin: *");
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$photo = $response["profilepic"];
// Obtain the original content (usually binary data)
$bin = base64_decode($photo);
// Load GD resource from binary data
$im = imageCreateFromString($bin);
// Make sure that the GD library was able to load the image
// This is important, because you should not miss corrupted or unsupported images
if (!$im) {
die('Base64 value is not a valid image');
}
// Specify the location where you want to save the image
$img_file = 'test/'.uniqid().'.jpg';
// Save the GD resource as PNG in the best possible quality (no compression)
// This will strip any metadata or invalid contents (including, the PHP backdoor)
// To block any possible exploits, consider increasing the compression level
imagejpeg($im, $img_file, 80);
$imgPath = 'http://serverip/'.$img_file;
?>
Please help me to identify the issue

Related

Image to base64 encoding issue - PHP

<?php
header("Content-type: image/jpeg;charset=utf-8'");
$path = 'example/source.jpg';
$da = file_get_contents($path);
$base64 = base64_encode($da);
$src = 'data:image/jpeg;charset=utf-8;base64,'.$base64;
echo '<img src="'.$src.'">';
?>
php v5.6.2
I tired copying the $src value in debug and pasted in img src value. still its not showing up.
what did i missed here?.
thanks in advance
header("Content-type: image/jpeg;charset=utf-8");
here you say to the browser i will send you an jpeg image,
then:
echo '<img src="'.$src.'">';
here you send HTML.
because you said it was a jpeg image, the browser will try to render your html as jpeg. since the ascii text-based HTML format is completely incompatible with the binary based jpeg-format, the browser will fail horribly when trying to render your image, and fail with some error (probably image is corrupt or something like that.)
you can either fix your Content-Type header to specify that you're sending HTML, then the browser will (probably successfully!) try to render it as such, eg:
header("Content-type: text/html;charset=utf-8");
or you can modify your code to actually send the image as jpeg, eg:
<?php
header("Content-type: image/jpeg");
$path = 'example/source.jpg';
readfile($path);
(btw a base64 encoded jpeg image will be about 33% larger than just the raw jpeg image, so if you want a fast pageload, or you want to save up on bandwidth, or you want to save up on ram, using readfile() is faster, requires less bandwidth, and requires less ram, both for the server and the client, compared to your embedded base64 approach.)
So maybe your problem is in your mime type. then try this code two solve:
$path = 'domain.com/example/source.jpg';
$content = file_get_contents($path);
$file_info = new \finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($path));
$base64 = base64_encode($content);
$src = 'data:'.$mime_type.';charset=utf-8;base64,'.$base64;
echo '<img src="'.$src.'">';
Note: its better to use path from full address domain, if you want to use from path use readfile()

PHP save PNG from base64 *rgba* string

I'm wondering if there is someone who can help me with this, i'm sending an image from my windows phone c# to php and i want to save the image.
The data connection works and i can receive the POST value
see: http://posttestserver.com/data/2014/01/23/19.41.40516059397 for the information the server receives.
i now want to save this base64 encoded RGBA string to a png or jpg (i would prefer png but i dont need the alpha value).
this is the code i have server side
//getimagecontents
$data = base64_decode(file_get_contents("php://input"));
//create an image from string
$im = imagecreatefromstring($data);
if ($im !== false) {
//add an header for the image
header('Content-Type: image/png');
//save the image
imagepng($im, 'upload/test.png');
imagedestroy($im);
echo "it worked!";
}
Hopefully someone can help me with this coz it's keeping me up all night :(
Thanks in advance :)
Make sure that you are receiving the data. If yes. then try once without base64_decode and upload directory is created in place that is where your image will be saved. If it is not created, you can not save image.
You should have received warnings in both cases indicating the problem. If this your dev environment, turn the warnings reporting on in php.ini or your script.
Another thing, why are you sending header for image when only you intend to save it to file system.
The image i was sending was too big for the server to handle...
As it was send as a RAW file...
converted it to a png and now works like a charm

PHP: Show JPG from Binary

I have a jpg blob thats been stored in an external DB and I'm looking to display that as an image via php. The issue is whenever I set the Content-Type to image/jpeg and echo out the blob I get the broken image icon when browsing to it.
I have tried making the file from scratch via sublime and that works when I save it as a hexadecimal file so I know the data is valid.
I have tried making the script create a file but it sets the charset=us-ascii so it won't get seen as a image file.
Does anyone have any experience with raw image binary files? anyone know how I can display the image or even save it out to a file?
Thanks in advance.
P.S. I would provide the binary but its just too big to put on here.
EDIT: (added some code)
<?php
header('Content-Type: image/jpeg;');
$data = 'some long string of hex';
// tried echoing it directly..
echo $data;
// and writing to a file...
file_put_contents('test.jpg', $data);
?>
After continuing research I found this post PHP: create file from an HEX string
With the following code I fixed the issue.
<?php
header('Content-Type: image/jpeg;');
$data = 'The hex data';
$data = pack('H*',$data);
$im = imagecreatefromstring($data);
imagejpeg($im);
?>
Try $im = imagecreatefromstring($data); The output it by imagejpeg($im);

Determine extension type using image stream

I am developing an API system for my uploading service (in PHP). At the current moment I support the option to send image data as binary data from file_get_contents, fread, etc, or by encoding it with 64 based system. I am attempting to determine the extension type of the image being uploaded to my service from this binary/base64 data. If it is base64 then I decode it and then process it.
I have the following at the moment:
// We need to figure it out ourselves
if ($type === "")
{
// Let's see if it is a base64 file
$base64 = $this->checkBase64Encoded($file_data);
// We got a 64 based file or binary
$type = $base64 === TRUE ? "base64" : "binary";
}
if ($type == "binary")
{
$im = imagecreatefromstring($file_data);
}
I want to see if it is possible to determine the image extension type for saving the file. What do you guys suggest? I read something about using getimagesize()? Although I am not sure about this. Is there no way to get around temporarily saving the file, processing it, and then renaming it?
I also planned to use this to test that the image was a valid image before i checked for extension but I wasn't exactly sure how to use the getimagesize() function:
try
{
// Get the width and height from the uploaded image
list($width, $height) = getimagesize($file['tmp_name']); // I'm not sure what to put here instead of $file['tmp_name']
}
catch (ErrorException $e)
{
// Ignore read errors
}
if (empty($width) OR empty($height))
{
// Cannot get image size, cannot validate
return FALSE;
}
Please feel free to ask for any clarifications if I was unclear. Thanks so much :)
You're looking for the fileinfo functions, particularly finfo_buffer().

How to create GD Image from base64 encoded jpeg?

I have an upload Api that as a response object delivers (along with other stuff inside a Json object) a base64 encoded jpeg image.
I create the encoded image as so:
$im; // gd image resource
ob_start();
imagejpeg($im);
$data = base64_encode(ob_get_clean());
The data then is put inside a form field using javascript and submitted.
How can I create a GD resource from that again so that I actually can save that image as a file?
Everything in PHP.
You can use imagecreatefromstring() function:
$data = base64_decode($_POST['image_as_base64']);
$formImage = imagecreatefromstring($data);
"String" does not mean a "real" string. In that case it means bytes/blob data.
How can I create a GD resource from that again so that I actually can save that image as a file?
Are you sure you need to do that extra step? How about:
file_put_contents('MyFile.jpg', base64_decode($_POST['MyFormField']));
I did by this way:
// input is in format: data:image/png;base64,...
$str="data:image/png;base64,";
$data=str_replace($str,"",$_POST['image']);
$data = base64_decode($data);
file_put_contents('tmp/'.mktime().'.png', $data);

Categories