php GD为图像添加填充

时间:2012-05-14 19:18:37

标签: php image-processing gd

我在网上发现了一些关于图像处理的关于PHP + GD的东西,但似乎没有人能给我我想要的东西。

我有人上传了任何尺寸的图像,我写的脚本将图像调整为不超过200像素宽,高200像素,同时保持宽高比。因此,最终图像可以是150像素×200像素。我想要做的是然后进一步操作图像并在图像周围添加一个遮罩,将其填充到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);

我想我需要在imagecopy()电话后立即使用imagecopyresampled()。这样图像已经是我想要的尺寸了,我只需要创建一个200 x 200的图像并将$ newImage粘贴到其中心(vert和horiz)。我是否需要创建一个全新的图像并合并这两个图像,或者是否有办法填充我已经创建的图像($newImage)?在此先感谢,我发现的所有教程都让我无处可去,而我在SO上找到的唯一适用的是android:(

1 个答案:

答案 0 :(得分:15)

  1. 打开原始图片
  2. 创建一个新的空白图片。
  3. 使用您想要的背景颜色填充新图像
  4. 使用ImageCopyResampled调整大小并复制以新图像为中心的原始图像
  5. 保存新图片
  6. 您也可以使用

    代替您的switch语句
    $img = imagecreatefromstring( file_get_contents ("path/to/image") );
    

    这将自动检测图像类型(如果安装支持图像类型)

    更新了代码示例

    $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);