I have a function which resizes and saves images based on configurable admin preferences. It takes only JPEG and PNG formats and saves them as JPEGs. I am trying to add the ability for this same function to convert the images to grayscale if a preference ($convertToGray) is set. The problem is that the conversion doesn't do anything. Here's the code:
//--------------------
// new image file name
//--------------------
$baseFile = 'baseImage' . $ext;
$newFile = '/path/to/new/location/' . $baseFile;
//-------------------
// get the image size
//-------------------
$oldSize = GetImageSize($baseFile);
//--------------------------------------
// which imageCreate function do we use?
//--------------------------------------
switch ($oldSize[2])
{
case 2: // jpg
$imFunc = 'ImageCreateFromJPEG';
break;
case 3: // png
$imFunc = 'ImageCreateFromPNG';
break;
}
//-------------------------------------------------
// open the image file and create a new source file
//-------------------------------------------------
$imOrg = $imFunc($baseFile);
$imNew = imageCreateTrueColor($newWidth, $newHeight);
//----------------------------------------------
// resave the new image to the artwork directory
//----------------------------------------------
ImageCopyResampled($imNew, $imOrg, 0, 0, 0, 0, $newWidth, $newHeight, $oldSize[0], $oldSize[1]);
if ( $convertToGray ) ImageCopyMergeGray($imNew, $imNew, 0, 0, 0, 0, $newWidth, $newHeight, 0);
ImageJPEG($imNew, $newFile, 90);
imageDestroy($imOrg);
imageDestroy($imNew);
I read in the PHP manual (in the user contributed notes) that if you wanted to simply convert an image to grayscale, you could use the same image resource for both the source and destination with the percent set to 0. I tried a few other methods, but the result is either an untouched image, or an all black image.
Any thoughts?