开发者

Using imagejpeg to save & serve image file

I'm doing a bit of an experiment with PHP + Image manipulation. I'm trying to convert some images into black and white versions. I'm mostly figured it out but have one slight issue.

In order to reduce the strain on the server, I wanted to save the B&W versions and only run the image filtering on images that haven't been run through the script before. So, I have something like this:

<?php 
h开发者_开发知识库eader("Content-type: image/jpeg");

$file = $_GET['img'];
$name = md5($file).".jpg";

if(file_exists("/path/to/file" . $name)) {

    ob_clean();
    flush();
    readfile("path/to/file" . $name);
    exit;

}
else {

 $image = imagecreatefromjpeg($file);

 imagefilter($image, IMG_FILTER_GRAYSCALE);
 imagejpeg($image, "/path/to/file" . $name);

 imagedestroy($image);
};

?> 

This does create the B&W versions of the file and save them to the server. The initial "if" statement is also working - it correctly serves the image if it already exists.

The issue is that for new images that are run through, this saves them but doesn't output them to the browser. What can I use/change in order to do that?

Also, this is my first time doing anything like this. Any general tips you have about doing the above would be appreciated.


A compact and correct form for above function can be:

<?php 
header("Content-type: image/jpeg");

$file = $_GET['img'];
$name = md5($file).".jpg";

if(!file_exists("/path/to/file" . $name)) {
 imagefilter($image, IMG_FILTER_GRAYSCALE);
 imagejpeg($image, "/path/to/file" . $name);
} else {
 $image = imagecreatefromjpeg("/path/to/file" . $name);
}

imagejpeg($image);
imagedestroy($image);

?> 


Because you are saving the image with imagejpeg() in the else part, your image will not be shown. So you have to add

readfile("/path/to/file". $name);

after imagedestroy() ;).


You could wrap the image-output code in a function - something like this (untested):

function output_image ( $image_file ) {
    header("Content-type: image/jpeg");
    header('Content-Length: ' . filesize($image_file));
    ob_clean();
    flush();
    readfile($image_file);
}

$file = $_GET['img'];
$name = md5( $file ) . ".jpg";
$image_file = "/path/to/file/" . $name;

if(!file_exists( $image_file )) {

   $image = imagecreatefromjpeg( $file );
   imagefilter( $image, IMG_FILTER_GRAYSCALE );
   imagejpeg( $image, $image_file );
   imagedestroy( $image );

}

output_image( $image_file );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜