php - 如果请求的图像在 php 中不存在,则生成正确大小的 error.jpg 图像

标签 php image error-handling

当源不存在时,对 image=90273497823 进行了非法请求
存在,您应该返回正确大小的占位符图像。

一个例子可能是:

<img src="resources/image.php?id=95648633&amp;x=160&amp;y=120&amp;color=1"  alt="kitty"/>

我没有让网页直接从我的服务器中提取图像,而是调用脚本 image.php 来服务这个请求,并在需要时处理异常。该脚本适用于所有存在的图像,但对于不存在的图像,脚本无法加载我拥有的 error.jpg 图像;让我相信我的错误处理是不正确的。

我希望我的脚本做的是检查文件是否存在,如果不替换为正确大小(不存在图像的相同大小请求)error.jpg

我的脚本如下。
<?php

header('Content-type: image/jpg');//override the return type
                              //so browser expects image not file
$id=$_GET['id'];//get file name
$new_width=$_GET['x'];//get width
$new_height=$_GET['y'];//get heigth
$color=$_GET['color'];//get colored version type
$filename=$id;//file id is set as file name
$filename.=".jpg";//append .jpg onto end of file name




// create a jpeg from the id get its size
$im=imagecreatefromjpeg($filename);

// get the size of the image
list($src_w, $src_h, $type, $attr)=getimagesize($filename);


/*
  Exception handling for when an image is requested and the file dosent exist
  in the current file system or directory. Returns file "error.jpg" correctly
  sized in the place of the  requested null file.
*/
if(!file_exists($filename))//(file_exists($filename) == false)
//(!file_exists($filename))
  {


    imagedestroy($im);//why do I have to destroy it, why cant I write over it?
    $im=imagecreatefromjpeg("error.jpg");
    list($src_w, $src_h, $type, $attr)=getimagesize($im);

  }

/*
  this function will resize the image into a temporary image
  and then copy the image back to $im
*/
if($new_width != '' && $new_height != '')

  {
     //MAKE A TEMP IMAGE TO COPY FROM
     $imTemp=imagecreate($new_width, $new_height);
     imagecopyresized($imTemp, $im, 0, 0, 0, 0, $new_width, $new_height, $src_w,
                     $src_h);
     imagedestroy($im);//free up memory space

     //COPY THE TEMP IMAGE OVER TO $im
     $im=imagecreate($new_width, $new_height);
     imagecopy($im, $imTemp, 0, 0, 0, 0, $new_width, $new_height);
     imagedestroy($imTemp);//free up memory space
  }

/*
  If the image being requested has color = 0, then we return a grayscale image,
  but if the image is already grayscale
*/
if($color == 0)
  {
     imagefilter($im, IMG_FILTER_GRAYSCALE);
  }

//What do we do if color = 0, but they want a colorized version of it???

imagejpeg($im);//output the image to the browser
imagedestroy($im);//free up memory space
?>

最佳答案

getimagesize采用文件名,而不是图像资源句柄。那可能是你出错的地方。

关于php - 如果请求的图像在 php 中不存在,则生成正确大小的 error.jpg 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126779/

相关文章:

android - Base64编码正在成为图像的一部分

php - 减少数据库 PHP MySQL 显示的图像数量

javascript - 追加时 Jquery V[g].exec 不是函数

php - 无法访问 Auth::check 我在 laravel 5.3 中的 View

image - 通过CSS使所有照片成为方形

php - Zend 导航和 Zend ACL

java - 如何克服 JpCap 问题?

r - 错误 : $ operator not defined for this S4 class

php - 同一页面上的 2 个表单 php

php - 如何使用 MySQL 中的数据填充复选框?