如何将图像资源编码为base64?

时间:2014-03-08 07:21:55

标签: php image base64 gd encode

我想知道是否有办法将图像编码为base64(如果它是资源) 例如,如果我使用GD

加载图像
    $image = imagecreatefromjpeg("captcha/$captcha-$num.jpg");

    // Add some filters
    imagefilter($image, IMG_FILTER_PIXELATE, 1, true);
    imagefilter($image, IMG_FILTER_MEAN_REMOVAL);

如果这是我的代码而不是保存图像并使用

显示它
<img src='someimage.jpg'>

我希望将其显示为数据URI而不必保存,例如

<img data='src="data:image/jpeg;base64,BASE64_HERE'>

我该怎么做?

2 个答案:

答案 0 :(得分:27)

$image = imagecreatefromjpeg("captcha/$captcha-$num.jpg");

// Add some filters
imagefilter($image, IMG_FILTER_PIXELATE, 1, true);
imagefilter($image, IMG_FILTER_MEAN_REMOVAL);

ob_start(); // Let's start output buffering.
    imagejpeg($image); //This will normally output the image, but because of ob_start(), it won't.
    $contents = ob_get_contents(); //Instead, output above is saved to $contents
ob_end_clean(); //End the output buffer.

$dataUri = "data:image/jpeg;base64," . base64_encode($contents);

答案 1 :(得分:0)

我为此写了一个函数。它还允许您即时更改输出图像格式。

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

// Creates an HTML Img Tag with Base64 Image Data
function gdImgToHTML( $gdImg, $format='jpeg' ) {
    ob_start();

    if( $format == 'jpeg'){
        imagejpeg( $gdImg );
    }
    else
    if( $format == 'png' ){
        imagepng( $gdImg );
    }
    else
    if( $format == 'gif' )
    {
        imagegif( $gdImg );
    }

    $image_data = ob_get_contents();
    ob_end_clean();

    return "<img src='data:image/$format;base64," . base64_encode( $image_data ) . "'>";
}