PHP output DataURI base64_encode

匆匆过客 提交于 2020-01-05 07:13:55

问题


I want to take a local image, resize it and output the dataURI. Why is my base64_encode code not working?

<?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:


imagecreatetruecolor returns an image resource, what you need to create the data uri is an image file, also the data uri format is data:[<MIME-type>][;charset=<encoding>][;base64],<data>

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

If you don't want to save a file to read, you can use imagepng and output buffering

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


来源:https://stackoverflow.com/questions/12127751/php-output-datauri-base64-encode

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