【发布时间】:2010-01-18 10:48:13
【问题描述】:
我有一个小的自定义 drupal 模块,可以裁剪用户个人资料图像:
$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% 的情况下,这就像一场梦,但偶尔会返回黑色图像。
这是一个问题的例子: http://5oup.net/sites/default/files/profile_pictures/405/t_Photo_8.jpg
和原始文件: http://5oup.net/sites/default/files/profile_pictures/405/Photo_8.jpg
知道可能出了什么问题吗?我的猜测是 imagecreatetruecolor() 线附近的东西?
提前致谢
詹姆斯
编辑
我似乎无法用原始用户图像重现错误,所以我现在真的不确定在这种情况下是什么原因造成的!有一个裁剪前的图像上传功能,我现在意识到这也可能是错误的根源,所以为了充分披露:
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);
}
【问题讨论】:
-
如果在代码前添加
ini_set('gd.jpeg_ignore_warning', 1);会发生什么? -
我已经尝试过了,有趣的是我无法使用提供的图像重现错误(请参阅编辑后的问题)。
-
imagecache 模块呢?无需重新发明轮子..
-
我们最初使用的是图像缓存,但可惜与服务器发生了某种冲突,所有图像都被破坏了,所以我们决定自己推出。
-
我这里有确切的问题。仅限特定照片。我相信这是与 GD 库相关的问题。