PHP 图像大小调整函数输出替换字符(很多次)



我已经将教程中的各种部分拼接在一起,以使用php来调整图像大小。这是我的图像调整大小功能(注意:图像的相对路径绝对正确)。

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

该函数的调用方式如下:

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

但是,图像不仅输出为默认损坏的img图标,而且还被数十个替换字符包围。

我想也许函数没有返回任何内容,所以我在函数的末尾插入:

return $dest_image;

没有效果。

谁能告诉我为什么我的功能没有按预期执行?

问题是当你使用 imagepng 和标头时,这仅适用于单独的脚本,例如:

<img src="theResizeScript.php"> 

这仅在脚本不存在其他输出时才有效。

无论如何,您可以使用ob_start和ob_end来捕获输出,如下所示:

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

当然,请记住在图像源标签中使用"data:image/png;base64"。

最新更新