2012-05-14 71 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