base64 encode PHP generated image without writing the image to disk -


i'm generating image in php use in users avatar.

i start hashing username , doing hexdec() conversion on various substrings of hash build set of rgb colours.

//create image $avatarimage = imagecreate(250, 250);  // first call imagecolorallocate sets background colour $background = imagecolorallocate($avatarimage, hexdec(substr($hash, 0, 2)), hexdec(substr($hash, 2, 2)), hexdec(substr($hash, 4, 2)));  //write image file $imagefile = 'image.png'; imagepng($avatarimage, $imagefile);  //load file contents , base64 encode $imagedata = base64_encode(file_get_contents($imagefile));  //build $src datauri. $src = 'data: ' . mime_content_type($imagefile) . ';base64,' . $imagedata; 

ideally i'd not use intermediate step , skip writing image out onto disk, although i'm not sure how best implement this?

i've tried passing $avatarimage directly base64_encode() expects string doesn't work.

any ideas?

you can use output buffering capture image data , use desired:

ob_start ( ); // start buffering imagepng($avatarimage); // output image $imagedata = ob_get_contents ( ); // store image data ob_end_clean ( ); // end , clear buffer 

for convenience create new function handle image encoding:

function createbase64fromimageresource($imgresource) {   ob_start ( );   imagepng($imgresource);   $imgdata = ob_get_contents ( );   ob_end_clean ( );    return base64_encode($imgdata); } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -