Reputation: 657
I have an image that I have created by combining images based on database data, and was wondering hw to convert that to base 64. I tried this but the characters returned can not be decoded into an image:
$encode ="data:image/png";
imagepng($image);
echo (base64_encode($encode));
I saw this among others but that requires a path that I don't have. Thanks for any help.
Upvotes: 1
Views: 5980
Reputation: 156
from manuals: http://php.net/manual/en/function.base64-encode.php#105200
/**
* Returns base64 encoded string prepended by "data:image/"
*
* @param $filename string
* @param $filetype string
* @return string
*/
function base64_encode_image($filename=string, $filetype=string)
{
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype
. ';base64,' . base64_encode($imgbinary);
}
}
Function code by luke at lukeoliff.com.
Function comments by me.
Upvotes: 0
Reputation: 324790
The following will allow you to get the image data without having to create a temporary file (I've had nightmares with temporary files before when too many users were online...)
ob_start(function($c) {return "data:image/png;base64,".base64_encode($c);});
imagepng($image);
ob_end_flush();
This will output something similar to:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAAAXNSR0IArs4c6QAAAAxQTFRFAGVygICA/8wz/+aZTn6FEAAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2wkZEwoSgxq4wwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAS0lEQVQI1w3EMQ3AMAwEwMdTEmWRSF68h0RQBIKl5vkUirdGX99wuKUPKkjJkfM4jueE+ivo7VW6wDCCq1VtEdtiIMY2BGlgwUU+P38ZK+RwskeQAAAAAElFTkSuQmCC
Which is suitable for use inside an <img src="..." />
.
// Define the function first
function ob_base64_encode($c) {
return "data:image/png;base64,".base64_encode($c);
}
// And pass its name as a string
ob_start('ob_base64_encode');
imagepng($image);
ob_end_flush();
Upvotes: 5
Reputation: 57346
You are encoding the string "data:image/png" - naturally you won't be able to decode it into an image. Assuming $image
contains valid image data, you should be able to simply do
imagepng($image, $temp_file_name);
base64_encode(file_get_contents($temp_file_name));
Upvotes: 1