Using imagejpeg to save and display an image file

I'm experimenting a bit with PHP + Image manipulations. I am trying to convert some images to black and white versions. I basically figured it out, but I have one small problem.

To reduce the load on the server, I wanted to save the B&W versions and only start filtering images on images that had not been previously executed through a script. 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 creates the B&W versions of this file and saves them on the server. The original if statement also works β€” it serves the image correctly if it already exists.

The problem is that to launch new images this saves them, but does not output them to the browser. What can I use / modify to do this?

, - . , , .

+3
3

:

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

?> 
+5

imagejpeg() else, .

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

imagedestroy();).

+2

- - (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 );
+1

Source: https://habr.com/ru/post/1778921/


All Articles