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


Produce a correctly sized error.jpg image if requested image does not exist in php

当源没有时,对 image=90273497823 发出非法请求存在,则应返回大小正确的占位符图像来代替它。

例如:

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

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

我希望我的脚本做的是检查文件是否存在,如果没有替换为正确大小(不存在的图像的相同大小的请求)错误.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 采用文件名,而不是图像资源句柄。那可能是你出错的地方。