2011-12-12 22 views
1

我想圖像中心到PHP imagecreatetruecolour中心圖像

$thumbnail_gd_image = imagecreatetruecolor(600, 300); 

命令的中間。如果用戶上傳100x50的圖片,我會生成一個較大的版本爲600x300的白色背景。現在,實際圖像被放置在左上角。我希望在600x300生成的圖像中間顯示此圖像。

另一方面,如果用戶上傳的圖片大於600x300,那麼我會調整大小以保持這些參數。

我正在構建一個圖像上傳/裁剪工具,但是裁剪區域總是是高度的兩倍,所以我需要可用裁剪區域在600x300之內進行任何細節裁剪。

可以這樣做嗎?小於600x300圖片的中心?

感謝

編輯:

嘗試下面的代碼,但它不喜歡它。

這是我的代碼(可能不是最乾淨的,但它需要快速半工作)。

if($source_image_width < 600 && $source_image_height < 300){ 
    $x = (600/2) - ($source_image_width/2); 
    $y = (300/2) - ($source_image_height/2); 
}else if($source_image_width > 600){ 
    $x = 0; 
    if($source_image_height < 300){ 
     $y = (300/2) - ($source_image_height/2); 
    }else{ 
     $y = 0; 
    } 
}else if($source_image_height > 300){ 
    if($source_image_width < 600){ 
     $x = (600/2) - ($source_image_width/2); 
    }else{ 
     $x = 0; 
    } 
    $y = 0; 
}else{ 
    $x = 0; 
    $y = 0; 
} 

上面的代碼在中心左側(約100px)稍微放置了一個400寬x 800高的圖像。任何圖像上的高度都可以很好地工作,但不是寬度。

回答

2

你可以嘗試:

$W = 600; 
$H = 300; 

$im = imagecreatefromjpeg($filename); 
list($w,$h) = getimagesize($filename); 
$x = ($W/2) - ($w/2); 
$y = ($H/2) - ($h/2); 

$newIm = imagecreatetruecolor($new_w, $new_h); 
// i know I could have used a better function for this, but... 
imagecopyresampled($newIm, $im, $x, $y, 0, 0, $w, $h, $w, $h); 

header("Content-type: image/jpeg"); 
imagejpeg($thumb); 

我沒有時間來測試它(對不起),但它應該工作,如果它沒有,只是告訴我,我會調試。

編輯1:

對於大圖像,您必須裁剪它。所有你需要做的可能只是

$W = 600; 
$H = 300; 

$im = imagecreatefromjpeg($filename); 
list($w,$h) = getimagesize($filename); 
$x = ($W/2) - ($w/2); 
$y = ($H/2) - ($h/2); 

$x = sqrt($x * $x); 
$y = sqrt($y * $y); 

$newIm = imagecreatetruecolor($new_w, $new_h); 
// i know I could have used a better function for this, but... 
imagecopyresampled($newIm, $im, $W > $w ? $x : 0, $W > $w ? $y : 0, $W > $w ? 0 : $x, $W > $w ? 0 : $y, $w, $h, $w, $h); 

header("Content-type: image/jpeg"); 
imagejpeg($thumb); 

嘗試,讓我知道結果。再一次,我沒有測試它,它可能以史詩般的方式失敗。

+0

嗨。謝謝回覆。這對於小於600x300的圖像非常適用,但是對於較大的圖像,它將它們置於偏離中心的位置。 – puks1978

+0

我已經更新了我的答案,對於更小的圖片和更大的圖片,這個概念很簡單,您可以將較小的圖片放在中心位置,或者將「中心」放在較大的圖片中(裁剪其他圖片)。如果你有興趣,請檢查一下。 – khael