How to Stop Gd2 from Washing Away the Colors Upon Resizing Images

How to stop GD2 from washing away the colors upon resizing images?

I've managed to further test this with Imagick:

Imagick sRGB Test

The left half of the image was processed with Imagick and the sRGB_IEC61966-2-1_no_black_scaling.icc color profile, the right half has no color profile associated and shows exactly the same if processed with Imagick or GD; here is the code I used:

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

$image = new Imagick('/path/to/DSC07275.jpg');

if (($srgb = file_get_contents('http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc')) !== false)
{
$image->profileImage('icc', $srgb);
$image->setImageColorSpace(Imagick::COLORSPACE_SRGB);
}

$image->thumbnailImage(1024, 0);

echo $image;

Here is a comparison of the several sRGB profiles available on the color.org website:

sRGB Comparison

It seems to me that the third profile produces the most vivid results, other than that I have no idea how one would make a definitive choice.


EDIT: Apparently, Imagick comes with a bundled sRGB profile, so you don't need to download the one from the Image Color Consortium website, the following code should handle all scenarios:

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

$image = new Imagick('/path/to/DSC07275.jpg');
$version = $image->getVersion();
$profile = 'http://www.color.org/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)
{
$image->profileImage('icc', $srgb);
$image->setImageColorSpace(Imagick::COLORSPACE_SRGB);
}

$image->thumbnailImage(1024, 0);

echo $image;

Photo has wrong colors after resized with PHP script

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";!

Images get rotated by 90 Whole resizing using gd2 in CodeIgniter

Do you have a OSx working machine?

In my case, a pic, that in my Mac was shown correctly, indeed was turned sideways, that is because OSX preview detects CellPhone orientation while the pic was taken....

The server not, neither windows machines... so that was driving me crazy...

Being or not this your case, you can use exif_read_data() function. This will give you orientation data if it exists on photo's metadata.

Check here: How to detect shot angle of photo, and auto rotate for website display like desktop apps do on viewing?

resizing image using gd2 in codeigniter

Please go through below, It will help your issue.

You can create another folder or new name for resize image. You are facing issue because while resizing image, the source image already in use. Hence either create new folder or change filename.

Create New Folder

$config['new_image'] = "path/to/new/folder/img".".".$extension;

Change New Image(Resized) name

$config['new_image'] = "newimg".".".$extension;

Let me know if it not works to you.

WordPress Image Resizing Reduces Quality of Image

Based on our discussions so far, I'd say you're experiencing a similar effect to that noted in this earlier question, though I don't know if your WordPress 3.4 installation will be using GD underneath.

Basically, what's happening is that your images have an embedded Adobe RGB colour profile, which is (arguably, I suppose) a perfectly reasonable thing for them to have, even if they're headed out onto the web. You may want to bear in mind that if the images are viewed in a browser that doesn't respect that kind of colour management, you may see some surprising results, and that generally it seems the advice would still be to prefer sRGB for the web.

I'm guessing that the resizing process used by your WordPress 3.4 installation isn't respecting the colour profile -- is, in fact, probably ignoring it -- which is why the colours are being mangled during the resize. Effectively it's outputting an image that should still be in Adobe RGB space, but dropping the colour profile, so the image is reinterpreted in sRGB, which is what's making things look muted.

There are two options, I'd say:

  • Look into some kind of resizing process that respects the colour profile of the images (as discussed in that earlier question, upgrading the GD library, if that's what's being used, or switching to an ImageMagick-based solution, say.) I've not tried it, but if you can install ImageMagick on your sever, it looks like this WordPress plugin will allow you to use it for the image resizing fairly painlessly. It specifically mentions respecting colour profiles on resize.

  • See if exporting your images in the sRGB colour space solves the resizing problem. That's probably the easiest solution, and is likely to work if what I think is going on is what's actually going on. Though the images are likely to end up without an embedded colour profile once they've gone through your resizer, virtually everything that sees them will assume they're sRGB anyway.

Fetching a file on a server, resizing with PHP GD2, security considerations

What are the security considerations when a server fetches a file from an untrusted domain?

The domain (host) and the file is not to be trusted. This spreads over two points:

  1. Transport
  2. Data

To transport the data safely, use a timeout and a size limit. Modern HTTP client libraries offer both of that. If the file could not be requested in time, drop the connection. If the file is too large, drop the data. Tell the user that there was a problem getting the file. Alternatively let the user handle the transport to that server by using the users browser and javascript to obtain the file. Then post it. Set the post limit with your script.

As long as the data is untrusted you need to handle it with caution. That means, you implement yourself a process that is able to run different security checks on the file before you mark it as "safe".

What are the security considerations when resizing an image that you don't trust with PHPs GD2 library?

Do not pass untrusted data to the image library then. See the step above, bring it into a safe state first.

The file will be stored on the server machine, and will be offered for download. I know I can't trust the MIME-Type header. Is there anything else I should be aware of?

I think you're still at the point above. How to come to safe from untrusted. Sure you can't trust the Content-Type header, however it's good to understand it as well.

You want to protect against the Unrestricted File Upload Vulnerability­OWASP.

  1. Check the filename. If you store the data on your server, give it a safe temporary name that can not be guessed upfront and that is not accessible via the web.
  2. Check the data associated with the filename, e.g. the URL information of the source of that file. Properly handle encoding.
  3. Drop anything that does not meet your expectations, so check the pre-conditions you formulate strictly.
  4. Validate the file data before you continue, for example by using a virus checker.
  5. Validate the image data before you continue. This includes file-headers (magic numbers) as well as that the file-size and file-content is valid. You should use a library that has specialized for the job, e.g. an image-file-format-malformation-checker. This is specialized software, so if this part of your business get into business. Many free software image file code exists, I leave this just for the info, you can't trust any recommendation anyway and need to get into the topic.
  6. If you plan to resize the image yourself, you need to make everything double-safe, because next to hosting you plan to process the data. So know what you do with the data first to locate potential fields of problems.
  7. Do logging and monitoring.
  8. Have a plan for the case that everything get's wrong.
  9. Consider to repeat the process for already existing files, so if you change your procedure, you are able to automatically apply the principles to uploads that were done in the past as well.
  10. Create a system for each type of work that is able to be cleaned after the work has been done. One system to do the download, one system to obtain the meta data etc.. After each action, restore the system from an image. If a single components fails, it won't be left over in an exploited state. Additionally if you detect a fail, you can take your whole system out of business until you have found the flaw.

All this depends a bit how much you want to do, but I think you get the idea. Create a process that works for you knowing where improvement can be added, but first create an infrastructure that is modular enough to deal with error-cases and which probably encapsulates the process enough to deal with any outcome.

You could delegate critical parts to a system that you don't need to care about, e.g. to separate processing from hosting. Additionally, when you host the images the webserver must not be clever. The more stupid a system is, the less exploitable it is (normally).

If hosting is not part of your business, why not hand it over to amazon s3 or similar stores? Your domain can be preserved via DNS settings.

Keep the libraries you use to verify images with up-to-date (which implicates you know which libraries are used and their versio, e.g. the PHP exif extension is making use of mbstring etc. pp. - track the whole tree down). Take care you're in the position to report flaws to the library maintainers in a useful way, e.g. with logging, storing upload data to reproduce stuff etc..

Get knowledge about which exploits for images did exist in the past and which systems/components/libraries (example, see disclaimer there) were affected.

Also get into the topic which are common ways to exploit something, to get the basics together (I'm sure you are aware, however it's always good to re-read some stuff):

  • Secure file upload in PHP web applications (Alla Bezroutchko; June 13, 2007; PDF)

Some related questions, assorted:

  • Is it important to verify that the uploaded file is an actual image file?
  • PHP Upload file enhance security


Related Topics



Leave a reply



Submit