Search code examples
phpimagejpeg

Photo has wrong colors after resized with PHP script


I'm using the following PHP function to resize big images to fit 500 px width:

<?php
function resizeImage($name) {
header('Content-type: image/jpeg');
$filename = "file.jpg";
$new_width = 500;
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, "file.jpg", 100);
}
?>

For some reason the colors on the resized image aren't exactly the same as before. They aren't as clear and strong as before. As you can see [picture removed] there's more red color and brilliance in the left (original) photo.

Why that? Is there something wrong with my script? Or is it a normal resizing effect?


Solution

  • This is the working code I have now:

    <?php
    // Call the function with: resizeImage("INSERT_YOUR_FILE_NAME_INCLUDING_SUFFIX_HERE");
    function resizeImage($file_name) {
    
    // File is located at: files/original/
    $filename = "files/original/".$file_name;
    
    // The width you want the converted image has
    $new_width = 500;
    
    // Calculate right height
    list($width, $height) = getimagesize($filename);
    $new_height = (($height*$new_width)/$width);
    
    // Get image
    $small = new Imagick($filename);
    
    // Resize image, but only if original image is wider what the wanted 500 px
    if($width > $new_width) {$small->resizeImage($new_width, $new_height, Imagick::FILTER_LANCZOS, 1);}
    
    // Some code to correct the color profile
    $version = $small->getVersion();
    $profile = "sRGB_IEC61966-2-1_no_black_scaling.icc";
    if((is_array($version) === true) && (array_key_exists("versionString", $version) === true)) {$version = preg_replace("~ImageMagick ([^-]*).*~", "$1", $version["versionString"]);if(is_file(sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version)) === true) {$profile = sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version);}}if(($srgb = file_get_contents($profile)) !== false){$small->profileImage("icc", $srgb);$small->setImageColorSpace(Imagick::COLORSPACE_SRGB);}
    
    // Safe the image to: files/small/
    $small->writeImage("files/small/".$file_name);
    
    // Clear all resources associated to the Imagick object
    $small->clear();
    }
    ?>
    

    Don't forget to either download the icc file from http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc and save it in the same directory as your resize file or change $profile = "sRGB_IEC61966-2-1_no_black_scaling.icc"; to $profile = "http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc";!