2

我想拍摄本地图像,调整大小并输出 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);
}
?>
4

1 回答 1

7

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());
于 2012-08-26T05:14:42.570 回答