PHP输出DataURI base64_encode

时间:2012-08-26 05:04:46

标签: php data-uri

我想拍摄一张本地图片,调整大小并输出dataURI。为什么我的base64_encode代码不起作用?

<?php
// Create an image instance

$imagearray = array('pop3', 'aboutme', 'passions', 'lindahlstudios', 'blog');

foreach ($imagearray as $key) {
    echo $key;

    //load image
    $im = imagecreatefrompng($key.'button4.png');

    //set width of resize
    $width = 70;
    $ratio = $width / imagesx($im);
    $height = imagesy($im) * $ratio;

    echo ' resizeTo-'.$width.'x'.$height.'<br>';

    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $im, 0, 0, 0, 0, $width, $height, imagesx($im), imagesy($im));

    //save image to file
    //imagepng($new_image, $key.'button4_'.$width.'.png');

    //print DataURI
    echo base64_encode($new_image);

    imagedestroy($new_image);
}
?>

1 个答案:

答案 0 :(得分:6)

imagecreatetruecolor返回图像资源,创建数据所需的内容uri是图像文件,数据uri格式为data:[<MIME-type>][;charset=<encoding>][;base64],<data>

echo 'data:image/png;base64,'.base64_encode(file_get_contents($new_image_file));

如果您不想保存要读取的文件,可以使用imagepng并输出缓冲

 ob_start();
 imagepng($new_image);
 echo 'data:image/png;base64,'.base64_encode(ob_get_clean());