Search code examples
phpimageresize-image

php image resize function outputs the replacement character (lots of times)


I have stitched together various pieces from tutorials to use php to resize an image. Here is my image resize function (note:the relative path to the image is definitely correct).

function resizeImg() {
  $source_image = imagecreatefrompng('images/myImage.png');
  $source_imagex = imagesx($source_image);
  $source_imagey = imagesy($source_image);

  $dest_imagex = 16;
  $dest_imagey = 22;
  $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
  imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
  header("Content-Type: image/png");
  imagepng($dest_image,NULL,9);
}

The function is called as follows:

<img src="<?php resizeImg(); ?>" alt=img">

However, not only does the image output as the default broken img icon, but it is surrounded by dozens of the replacement character �.

I thought perhaps the function was not returning anything, so I inserted at the end of the function:

return $dest_image;

with no effect.

Can anybody please tell me why my function doesn't perform as anticipated?


Solution

  • The problem is when you use imagepng and headers, this only works in a separate script, like:

    <img src="theResizeScript.php"> 
    

    And this only works if is not present other output for the script.

    Any way, you can use ob_start and ob_end to capture the output like this:

    <img src="data:image/png;base64,<?php echo resizeImg(); ?>" alt="img"/>
    
    <?php
    function resizeImg() {
    
        $source_image = imagecreatefrompng('images/image.png');
        $source_imagex = imagesx($source_image);
        $source_imagey = imagesy($source_image);
    
        $dest_imagex = 16;
        $dest_imagey = 22;
        $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
        imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
    
        ob_start();
        imagepng($dest_image,NULL,9);
        $image_data = ob_get_contents();
        ob_end_clean();
    
        return base64_encode($image_data);
    }
    

    Of course remember to use the "data:image/png;base64" in your image source tag.