2017-04-13 196 views
1

我有圖片150x150px。我需要通過增加源圖像周圍的透明區域來創建圖像800x350px,指示新圖像中的座標:50px from top,50px從左邊開始。如何將PNG圖像的透明區域增加至特定尺寸?

source image

new image from source

我曾嘗試:

// the needed sizes of image 
$imgWidth = 800; 
$imgHeight = 441; 

// currrent sizes of PNG image 
$wmSize = getimagesize("wm2.png"); 
$wmWidth = $wmSize[0]; // 724 
$wmHeight = $wmSize[1]; // 144 

// current PNG image 
$wm = imagecreatefrompng("wm2.png"); 
imagesavealpha($wm, true); 
imagealphablending($wm, true); 

// new empty image 
$new_empty_image = imagecreate($imgWidth, $imgHeight); 

// opacity 0 
$transparent = imagecolorallocatealpha($new_empty_image, 255, 255, 255, 127); 
imagefilledrectangle($new_empty_image, 0, 0, $imgWidth, $imgHeight, $transparent); 

imagecopy($new_empty_image, $wm, $imgWidth, $imgHeight, 0, 0, $wmWidth, $wmHeight); 

imagepng($new_empty_image, 'new.png'); 

,但我得到沒有源PNG圖像只是一句形象:

enter image description here

所以,最後一個工作版本是:

$width = 800; 
$height = 441; 

// PNG image 
list($wm_width, $wm_height) = getimagesize('wm.png'); 
$wm = imagecreatefrompng('wm.png'); 

// new empty image 
$new_empty_image = imagecreatetruecolor($width, $height); 
$transparent = imagecolorallocatealpha($new_empty_image, 255, 255, 255, 127); 
imagefill($new_empty_image, 0, 0, $transparent); 

// Put wm on top of new image. 
imagecopy($new_empty_image, $wm, 50, 150, 0, 0, $wm_width, $wm_height); 

imagealphablending($new_empty_image, false); 
imagesavealpha($new_empty_image, true); 

imagepng($new_empty_image, 'new.png'); 
+1

你嘗試過這麼遠嗎?任何代碼沒有? – Yolo

回答

0

這裏是一個全功能和測試的例子:

$width = 800; 
$height = 441; 

// PNG image 
list($wm_width, $wm_height) = getimagesize('wm.png'); 
$wm = imagecreatefrompng('wm.png'); 

// new empty image 
$new_empty_image = imagecreatetruecolor($width, $height); 
$transparent = imagecolorallocatealpha($new_empty_image, 255, 255, 255, 127); 
imagefill($new_empty_image, 0, 0, $transparent); 

// Put wm on top of new image. 
imagecopy($new_empty_image, $wm, 50, 50, 0, 0, $wm_width, $wm_height); 

// Optional??? This code seems to be needed in some system and not in others. 
imagealphablending($new_empty_image, false); 
imagesavealpha($new_empty_image, true) 
// ?? Optional 

imagepng($new_empty_image, 'new.png'); 
+0

感謝您的評論。我已更新任務。沒有成功... –

+0

看起來圖像複製功能應該使用50,100代替寬度,高度。 – danielson317

+0

再次更新了anwwer。這個在我的本地服務器上效果很好。我將imagecreate更改爲imagecreattruecolor和imagefillrect與imagefill – danielson317