Hello again!
I have a small custom drupal module which crops user profile images:
$folder = 'sites/default/files/profile_pictures/'.$uid.'/';
$filename = $_POST['filename'];
$orig_w = 480;
$orig_h = $_POST['height'];
$targ_w = 150;
$targ_h = 92;
$ratio = $targ_w / $targ_h;
if(isset($_POST['form_sent']))
{
$src = imagecreatefromjpeg($folder.$filename);
$tmp = imagecreatetruecolor($targ_w, $targ_h);
imagecopyresampled($tmp, $src, 0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($tmp, $folder.'t_'.$filename,100);
$full_path = $folder.'t_'.$filename;
imagedestroy($tmp);
imagedestroy($src);
// database stuff
} else {
return 'Nothing to crop!';
}
95% of the time this works like a dream, however occasionally it will return a black image.
Here is an example of the problem: http://5oup.net/sites/default/files/profile_pictures/405/t_Photo_8.jpg
and the original file: http://5oup.net/sites/default/files/profile_pictures/405/Photo_8.jpg
Any idea what might be going wrong? My guess is something around the imagecreatetruecolor() line?
Thanks in advance
James
EDIT
I can't seem to reproduce the error with the orginal user image so I'm now really unsure what has caused it in this case! There is a pre-crop image upload function which I now realise could also be the source of the error, so in the interests of full disclosure:
if( isset($_POST['form_sent']) )
{
$imageFile = $_FILES['image']['tmp_name'];
$filename = basename( $_FILES['image']['name']);
$filename = preg_replace("/[^A-Za-z0-9 .]/", '', $filename);
$filename = str_replace(" ", '_', $filename);
$filename = urlencode($filename);
$img_info = getimagesize($imageFile);
if (filesize($imageFile) > 510000) {
drupal_set_message('Image too large. Please upload a file 500kb or less.', 'error');
$image_form = '<a href="/avatar">Choose a different image</a>';
$output = array(
'image_form' => $image_form
);
return serialize($output);
}
list($width, $height) = getimagesize($imageFile);
switch ($img_info['mime']) {
case 'image/png':
$src = imagecreatefrompng($imageFile);
break;
case 'image/jpeg':
case 'image/jpg':
$src = imagecreatefromjpeg($imageFile);
break;
case 'image/gif':
$src = imagecreatefromgif($imageFile);
break;
default:
drupal_set_message('File type not allowed. Please upload a jpg, gif or png.', 'error');
$image_form = '<a href="/avatar">Jpg, gif or pngs only</a>';
$output = array(
'image_form' => $image_form
);
return serialize($output);
break;
}
$orig_h = ($height/$width)* $orig_w;
$tmp = imagecreatetruecolor($orig_w, $orig_h);
imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
}