简体   繁体   中英

Convert GD output to base64

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.

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

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>';
}

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