Search code examples
phpdata-uri

PHP output DataURI base64_encode


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);
}
?>

Solution

  • 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());