Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
header("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.

like image 692
V. Arora Avatar asked Dec 28 '22 04:12

V. Arora


1 Answers

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

?> 
like image 145
Stoic Avatar answered Jan 09 '23 06:01

Stoic