简体   繁体   中英

PHP convert an image made in the file into base64

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.

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="..." /> .

Edit For PHP < 5.3 without anonymous functions:

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM