0

I've made this piece of code, it will re-size images on the fly, if it can't find the requested image, and then stores it.

The only problem with this is that the output jpg image has a low quality.

I was wondering if there is something I need to change to improve the image quality.

if (isset($_GET['size'])) {
    $size = $_GET['size'];
}

if (isset($_GET['name'])) {
    $filename = $_GET['name'];
}

$filePath = "files/catalog/" . urldecode($filename);

// Content type

header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filePath);

if ($_GET["name"] && !$size) {
    $newwidth  = $width * $percent;
    $newheight = $height * $percent;

} else if ($_GET["name"] && $size) {
    switch ($size) {
        case "thumbs":
            $newwidth  = 192;
            $newheight = 248;
            break;
        case "large":
            $newwidth  = 425;
            $newheight = 550;
            break;
    }
}

$resizedFileName = $filename; 
$resizedFileName = str_replace(".jpg", "", $resizedFileName) . ".jpg";
$resizedFilePath = "files/catalog/" . urldecode($resizedFileName);


if (!file_exists($resizedFilePath)) {
    // Load
    $thumb  = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filePath);

    // Resize
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output
    imagejpeg($thumb, $resizedFilePath);
    //file_put_contents($, $binarydata);

    $imageContent = file_get_contents($resizedFilePath);
    echo $imageContent;

} else {
    $imageContent = file_get_contents($resizedFilePath);
    echo $imageContent;
}
Yasser1984
  • 2,401
  • 4
  • 32
  • 55

3 Answers3

1

Instead of imagecopyresized() you must use imagecopyresampled() and imagejpeg() function has third optional parameter and you can specify quality.

ioseb
  • 16,625
  • 3
  • 33
  • 29
0

Probably because you are using imagejpeg() wrong, the second variable in the functions stands for the quality in percentage!

Max Allan
  • 640
  • 5
  • 18
0

You want imagecopyresampled(). resize works by throwing away unecessary pixels. resampled() will average things out and produce much smoother results.

Marc B
  • 356,200
  • 43
  • 426
  • 500