How to save the jpg file from base64 data - php

I have the base 64 data for my images and I want to save them in my local machine as JPG Files.
My base 64 code starts with
data:image/jpg;base64,/...
I already tried to save it by the following code:
file_put_contents('MyFile.jpg', base64_decode($imgData1));
But I cannot open the created image; it says "the file appears to be damaged, corrupt, or is too large". Could you please let me know what I'm missing.
Also if you need any more clarification, please let me know which part you need more clarification.

Get rid of the prefex before calling base64_decode.
<?php
// get rid of everything up to and including the last comma
$imgData1 = substr($imgData1, 1+strrpos($imgData1, ','));
// write the decoded file
file_put_contents('MyFile.jpg', base64_decode($imgData1));

This looks not just base64 but PHP stream wrapper data.
file_put_contents('MyFile.jpg', file_get_contents('data:image/jpg;base64,/...'));

You need to use imagecreatefromstring and imagejpeg, here's an example:
$imageStr = base64_decode($imgData1);
$image = imagecreatefromstring($imageStr);
imagejpeg($image, $somePath);

Related

Why PHP cuts off base64 image?

I'm trying to use php to save a base64 image on my server.
But every time I run my code, I get this error:
PHP Warning: file_get_contents(data:image/gif;base64R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P goOXMv8 fhw/v739/f 8PD98fH/8mJl fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8 QePLl38MGBr8JCP zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/ MjMUcAN8zM/9wcM8ZGcATEL QePdZWf/29uc/P9cmJu9MTDImIN /r7 /vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo Pj/ pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP 8vH9QUK vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl LFt8dgUE9PT5x5aHBwcP AgP WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA in my-file.php
I POST the base64 image via AJAX to my PHP page and this what I have in my PHP page:
$base64_string = $_POST['logo'];
$output_file = 'image.jpg';
file_put_contents('../logos/'.$output_file, file_get_contents($base64_string));
When I look inside the logos folder, I see the image.jpg being created but it has no content.
when I look at the error that PHP throws out, the base64 image seems to be a lot shorter than the actual base64 that I am POSTing!
Can someone please advice on this issue?
I also changed my server's post_max_size to 120M but I still get the same error.
EDIT:
Here's the base64 image that I am sending to my PHP page:
data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQ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10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==
Of course this is not working.
It's because you try to read a file at path $base64_string.
$base64_string = $_POST['logo'];
$output_file = 'image.jpg';
file_put_contents('../logos/'.$output_file, $base64_string);
Will work.

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

Uploading PNG file to nginx server via HTTP_RAW_POST_DATA results in corrupted image

I'm trying to debug this issue by posting raw PNG image data to the server with the help of Postman. Here's a screenshot, which might help to understand the issue:
On the server I'm receiving the file as follows:
$png = $GLOBALS["HTTP_RAW_POST_DATA"];
Then I write the data to a new file:
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $png);
fclose($fh);
The file gets saved correctly, but it now has a different file size,
417KB instead of 279KB which is the size of the original file.
Now of course, I can't do any image operation as none of the functions (such as getimagesize which returns bool(false)) recognizes the file as a valid image.
I have debugged this process to a point where the issue must be somewhere in the file operations, but I don't understand why the file just doesn't result in the very same file type and size as the original, when the only thing I am doing is using the same raw data.
UPDATE:
I've now compared the encodings of the original file with the uploaded one,
and the former is in ISO-8859-1 and it displays correctly, the latter is in UTF-8 and has about 138kB more in file size.
Now I've achieved to convert the file on the server to ISO-8859-1.
fwrite($fh, iconv("UTF-8", "ISO-8859-1", $png));
The resulting file does now have the same output file size (279kB),
but it is still not recognized as a PNG image, some information seems to still get lost.
UPDATE (1):
I've been able to examine the issue further and found out, that the original file is exactly 4 bytes bigger than the generated file, thus the resulting PNG seems to be corrupted.
UPDATE (2):
I'm now able to save the file and open it as a valid PNG. The following code seems to be saving the image correctly:
$input = fopen("php://input","r+");
$destination = fopen($myFile, 'w+');
stream_copy_to_stream($input, $destination);
fclose($input);
fclose($destination);
However when trying to open the file with the imagecreatefrompng function I get a 500 error. I'm now trying to figure out if it's a memory issue in PHP.
Problem might be the way you test your POST by copying the "binary" data into a text field.
If you paste the same data into a text editor you won't get a valid image file either when saving this with the png extension.
Try to build a simple form with file field to test your upload
I use nginx for uploads and haven't had a problem, but I use the standard PHP way of uploading files as per: http://www.php.net/manual/en/features.file-upload.post-method.php
I would suggest trying that.
Try using: < ?php $postdata = file_get_contents("php://input"); ?>
To get the raw data. I use it some times to get data sent from a ajax post on cake.

base64 Pic Upload and Crop Situation PHP

I am trying to take a pic upload from a mobile device to a server. We are building with PhoneGap (Javascript), so we are having turn it into a string in order to send it to the server. I am having problems once I receive it, to turn it back into a readable image file.
Simply put, I need to take a string and a file name sent to me, decode it, convert it into a .png, then crop it into a circular image.
This is what I have going on currently
if (isset($_POST['file']))
{
//Result variable
$result = false;
$pic = base64_decode($_POST['file']);
$filename = $_POST['filename'];
if (strlen($pic) > 9 )
{
$fh = fopen("/var/www/pics/events/".$filename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
I think I can get the rest of the code to work if I can figure out what I am doing wrong here that makes it not save properly as a image file? The file uploads correctly, but it stores with out an extension, and when I point to it in my browser, it comes up like it is supposed to be an image file, but never displays the image. That little broken picture icon with the colored shapes is what I get when I direct to it's location.
Do I need to be aware of what image type is being sent during this process at all? How is it knowing if it is a .gif, .jpg/jpeg, .png, etc...?
Thanks in advance for any help!
Nathan
For Security reasons you should sanitize the file name to prevent directory traversal.
On a brighter note, make sure the file is saved with the proper extension; if you are already saving with the correct extension you could have an encoding issue from the app.
If neither of the previous possibilities are the case make sure that your String Size does not exceed the maximum POST size limit in your php.ini; if that is the case increase the size limit.

Image creation using php

Am trying to create a video clip using .jpg images and ffmpeg, am creating .jpg images as below:
$str=$_REQUEST['data_array'];//gets the base64 encoded image data;
$count =$_REQUEST['count'];//gets number of images i've to create;
$edited_str=substr($str,23,strlen($str)-1);//
$edited_str=base64_decode($edited_str);
$f=fopen("Images/temp".$count.".jpg","w");//am creating temp.jpg file
fwrite($f,$edited_str);//placing my decoded data into file
fclose($f);
are the images am creating above different from normal .jpg images?
This line:
$edited_str=substr($str,23,strlen($str)-1);
makes it different. If this is the full base64 sting of the file, then this cuts it up and corrupts it. Maybe you are adding some stuff on the front.
If you are just removing stuff from the front that was added, then it should be the same as the original file that was encoded with base64.
If you want to get the information this way from another page, I suggest using $_POST as opposed to $_REQUEST for a number of reasons.
EDIT: I wouldn't say video manipulation in php is impossible. I think there is even a toolkit... here's one:
http://phpvideotoolkit.sourceforge.net/
which states:
It can perform video format conversion, extract video frames into separate image files, and assemble a video stream from a set of separate video images.
Haven't tested it, but plan to try it out one day.
EDIT2: On the php site, there were some issues that you could try, but to help more, there needs to be more information. Check with a file directly to make sure it's being sent and decrypted properly.
I haven't got to test any of these yet.
One piece of advice was for large files use:
$decodedstring=base64_decode(chunk_split($encodedstring));
Another was if you use javascript canvas.toDataURL() then you need to convert spaces back to pluses:
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
http://php.net/manual/en/function.base64-decode.php

Categories