PHP save PNG from base64 *rgba* string - php

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

Related

Upload image from Android app through php move_uploaded_file

I'm trying to upload image file from my android app to a server. This is my php file that is processing incoming images from my website and iOS app to be used in move_uploaded_file function:
<?php include '../../../init.php';
$post_id = $_GET['post_id'];
$image_temp = $_FILES['image']['tmp_name'];
$image_name = $_FILES['image']['name'];
$image_ext = strtolower(end(explode('.', $image_name)));
upload_page_image($image_temp, $image_ext, $post_id);
Now, in android I came up to the point when I have Base64 encoded string:
params.put("image",imageToString(bitmap));
Then, I bring this to my PHP file like this:
<$php
....
$image = base64_decode(_POST['image']);
...
But now, how do I brake it in to $_FILES['image']['temp_name'] and $_FILES['image']['name']? All the other examples I went through are using file_put_contents. I need it to be move_uploaded_files.
Any help is appreciated.
Thanks
this worked for me enter link description here
You must submit image using Multipart Form Data for use move_uploaded_files in php
Ok, that was the most difficult stuff I ever went through. The problem is that when I use php function file_put_contents(), it first makes everything easy on android app side, just convert bitmap to Base64 and pass it to php file. But... one very important thing got lost in this process.... it's that $exif['Orientation'] when using exif_read_data. This parameter is not there any more.
Now, when going back to android app and trying to get image orientation before sending the file to php, the standard function such as below:
ExifInterface exifReader = new ExifInterface(mFilePath);
exifReader.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
.. or similar doesn't work. It always returns 0. ALWAYS
Solution came from using Glide https://github.com/bumptech/glide library and get current image orientation using:
InputStream is = getActivity().getContentResolver().openInputStream(originalUri);
int orientation = new ImageHeaderParser(is).getOrientation();
Once you get orientation, you pass image as Base64 and orientation number and then process upload and do orientation change and so on.

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);

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.

working with image from imagecreatefromstring PHP

So i have an iphone app that that uploads an image to my webserver and i looked around and people seem to be doing something like
$data = file_get_contents($_FILES['file']['tmp_name']);
$image = imagecreatefromstring($data);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
I looked at the php docs, but i still don't understand what the header() does; does it convert the image into whatever format i want?
And for the imagepng(), where is the image outputted to? memory? is that why i need the imagedestroy()?
and where would i put in
move_uploaded_file()
Thanks in advance!
This code is intended to return as output an image - you could use it as a valid src for an image tag. That is, you could do this:
<img src="thatfile.php?something=1" />
The headers tell the browser that the data the server is going to send is an image (a PNG image, specifically).
In your example code, the file never actually gets written anywhere: the data stays in memory until the script ends, then it is simply "forgotten". imagedestroy frees up the memory and is good practice, but it really isn't necessary since the memory will be garbage collected after the request ends. If you want to preserve the image in a file, you'd have to use one of the related functions such as imagepng: http://www.php.net/manual/en/function.imagepng.php. The only difference between writing the file or not in your example code is the lack of a second argument for imagepng - second argument would be the desired file path.
It would help to read through the docs on this entire subject to gain a firm grasp of how these functions work and what each does. There are plenty of demos on the doc pages that show this in action.
This particular example gets the image uploaded through POST from the $_FILES array and simply outputs it back to the browser. The header is there to inform the browser that the content following is a PNG image.
Since you create an image from a string, it doesn't have "an extension". It's just an image resource at this point. You can create an actual file from it using imagepng, imagejpeg or any of the other methods to save an image resource to a file. You decide the extension (and file name) at that stage yourself.
E.g.:
imagepng($image, 'path/to/file.png');
and where would i put in move_uploaded_file()?
You wouldn't, since you don't have an uploaded file, only a string.
Header is purely for the server to let the browser know "Oh hey this is a png image please render it so"
imagepng encodes it into the png format and "prints" to the output
imagedestroy frees the memory taken by the image resource.
If you need to force extension you can use mod_rewrite
Here's a sample couple lines from my .htaccess:
RewriteEngine on
RewriteRule images/000000/00FF00/newmyinfo.jpg images/newmyinfo.php?bgcolor=000000&color=00ff00 [L]
Hope this helps!

Have GD get image from binary string

I have a database that stores images in a MySQL BLOB field. I setup a script that selects and displays the images based on an ID in the URL, and I also made it so if you append ?resize=800x600, it would resize the image (in this case, to 800x600).
The host that I use doesn't have Imagemagick installed and won't let me do it myself, so I need to use PHP's GD library to resize the image.
But I've yet to find a function like Imagick's readImageBlob(), so I can't edit the binary string that I get from the database without first creating a temporary file, editing it, getting the binary string from it, sending it to the browser, and then deleting it (which is waaaay too many steps, especially since this will be getting a few thousand hits when it goes into production).
So my question is, is there any way to replicate readImageBlob with PHP's GD without going through the temporary file solution?
imagecreatefromstring() should do the trick. I think the function example in the manual is almost exactly what you need:
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
Where $data is your binary data string from the database.

Categories