Convert GD output to base64

南楼画角 提交于 2019-11-28 05:00:38

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>';
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!