2012-05-14 72 views
10

我在网上发现了一些关于PHP + GD的图像处理方面的东西,但没有一个看起来让我知道我在找什么。php GD为图像添加填充

我有人上传了任何尺寸的图片,我写的脚本将图片大小调整为不超过200px宽×200px高,同时保持纵横比。因此,最终的图像可能是150px×200px。我想要做的是进一步操纵图像,并在图像周围添加一层地毯,以便将其填充到200px×200px,同时不影响原始图像。例如:

Unpadded Image 143x200

Padded image 200x200

我一定要得到的图像大小的代码是在这里,我已经尝试了一些东西,但我绝对有实现增加填充的二次加工的问题。

list($imagewidth, $imageheight, $imageType) = getimagesize($image); 
$imageType = image_type_to_mime_type($imageType); 
$newImageWidth = ceil($width * $scale); 
$newImageHeight = ceil($height * $scale); 
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); 
switch($imageType) { 
    case "image/gif": 
     $source=imagecreatefromgif($image); 
     break; 
    case "image/pjpeg": 
    case "image/jpeg": 
    case "image/jpg": 
     $source=imagecreatefromjpeg($image); 
     break; 
    case "image/png": 
    case "image/x-png": 
     $source=imagecreatefrompng($image); 
     break; 
} 
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height); 
imagejpeg($newImage,$image,80); 
chmod($image, 0777); 

我想我需要imagecopyresampled()呼叫后立即使用imagecopy()。这样图像已经是我想要的尺寸,我只需要创建一个精确到200 x 200的图像并将$ newImage粘贴到该图像的中心(vert和horiz)。我是否需要创建一个全新的图像并合并这两个图像,还是有一种方法来填充我已经创建的图像($newImage)?在此先感谢,所有的教程,我发现促使我无处,而只适用一个我发现了所以是为Android :(

回答

13
  1. 打开原图
  2. 创建一个新的空白图像。
  3. 填入新图像与背景颜色你的缺乏
  4. 使用ImageCopyResampled来调整&复制中心到新的图像
  5. 保存新图像与原始图像

而不是你的switch语句中,你也可以使用

$img = imagecreatefromstring(file_get_contents ("path/to/image")); 

这会自动检测图像类型(如果IMAGETYPE是支持你的安装)

更新了代码示例

$orig_filename = 'c:\temp\380x253.jpg'; 
$new_filename = 'c:\temp\test.jpg'; 

list($orig_w, $orig_h) = getimagesize($orig_filename); 

$orig_img = imagecreatefromstring(file_get_contents($orig_filename)); 

$output_w = 200; 
$output_h = 200; 

// determine scale based on the longest edge 
if ($orig_h > $orig_w) { 
    $scale = $output_h/$orig_h; 
} else { 
    $scale = $output_w/$orig_w; 
} 

    // calc new image dimensions 
$new_w = $orig_w * $scale; 
$new_h = $orig_h * $scale; 

echo "Scale: $scale<br />"; 
echo "New W: $new_w<br />"; 
echo "New H: $new_h<br />"; 

// determine offset coords so that new image is centered 
$offest_x = ($output_w - $new_w)/2; 
$offest_y = ($output_h - $new_h)/2; 

    // create new image and fill with background colour 
$new_img = imagecreatetruecolor($output_w, $output_h); 
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red 
imagefill($new_img, 0, 0, $bgcolor); // fill background colour 

    // copy and resize original image into center of new image 
imagecopyresampled($new_img, $orig_img, $offest_x, $offest_y, 0, 0, $new_w, $new_h, $orig_w, $orig_h); 

    //save it 
imagejpeg($new_img, $new_filename, 80); 
+0

对switch语句的洞察力非常好,这肯定比我的switch语句更有效率。尽管如此,我对imagecopyresampled感到困惑。原始图像的大小调整已完成且正在运行,只是将其粘贴到200x200像素的背景上。我的理解是,imagecopyresampled会再次调整原始图像的大小? – MaurerPower

+0

查看更新的答案 – bumperbox

+0

这很棒!我最终使用了一些修改后的版本来获得我想要的确切结果,但这使我明确地走上了正确的道路!谢谢bumberbox!接受和upvoted! – MaurerPower