27

Well, my question is very simple, i just wanna convert the output of imagepng/imagejpg to base64, how i can do this ? the correctly way is with capturing output buffer ? thanks.

2 Answers2

63

imagejpeg/imagepng doesn't return any data, they write the image data directly to the output stream (or to a file).

If you'd like to capture this data encoded as base64 the easiest method is to use PHPs Output Control Functions, and then use base64_encode on the $image_data.

ob_start (); 

  imagejpeg ($img);
  $image_data = ob_get_contents (); 

ob_end_clean (); 

$image_data_base64 = base64_encode ($image_data);
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
6

The most common use case for base64 encoded images is HTML output. I'd like to offer a more complete solution for this case. I have also added the ability to switch output image formats.

// Example
$gdImg = imagecreate( 100, 100 );
imagecolorallocate( $gdImg, 0, 0, 0 );
echo gdImgToHTML( $gdImg );
imagedestroy( $gdImg );

// Create an HTML Img Tag with Base64 Image Data
function gdImgToHTML( $gdImg, $format='jpg' ) {

    // Validate Format
    if( in_array( $format, array( 'jpg', 'jpeg', 'png', 'gif' ) ) ) {

        ob_start();

        if( $format == 'jpg' || $format == 'jpeg' ) {

            imagejpeg( $gdImg );

        } elseif( $format == 'png' ) {

            imagepng( $gdImg );

        } elseif( $format == 'gif' ) {

            imagegif( $gdImg );
        }

        $data = ob_get_contents();
        ob_end_clean();

        // Check for gd errors / buffer errors
        if( !empty( $data ) ) {

            $data = base64_encode( $data );

            // Check for base64 errors
            if ( $data !== false ) {

                // Success
                return "<img src='data:image/$format;base64,$data'>";
            }
        }
    }

    // Failure
    return '<img>';
}
Lachmanski
  • 111
  • 3
  • 5
  • Do we need to call `imagedestroy($gdImg)` or will `ob_end_clean()` take care of that for us? – user3442612 Apr 03 '17 at 11:01
  • @user3442612 It is good practice to manually destroy images after use. I don't believe it's pertinent for this short sample, but I will add it for the sake of doing things "the right way". Thanks. – Lachmanski Apr 04 '17 at 12:13