2011-09-30 93 views
6

我有很多JPEG圖像,我想使用PHP將其轉換爲PNG圖像。 JPEG將由客戶端上傳,所以我不能相信他們確保它們的格式正確。使用PHP將JPEG轉換爲透明PNG

我也想讓他們的白色背景透明。

PHP有什麼功能可以用來實現這個功能嗎?

回答

8

後嘗試不同的解決方案,並做一些更多的研究, 幾天這就是我發現我工作。

$image = imagecreatefromjpeg('image.jpg'); 
imagealphablending($image, true); 
$transparentcolour = imagecolorallocate($image, 255,255,255); 
imagecolortransparent($image, $transparentcolour) 

imagealphablending($image, true);很重要。

使用imagesavealpha($f, true);在前面的回答中提到的肯定行不通,似乎確實防止您的背景透明...

爲了輸出正確的標題透明圖像。

<?php 
    header('Content-Type: image/png'); 
    imagepng($image, null, 1); 
?> 
6
$f = imagecreatefromjpeg('path.jpg'); 
$white = imagecolorallocate($f, 255,255,255); 
imagecolortransparent($f, $white); 

更多細節here

+6

假設這會工作,記住,JPG是一種有損格式。這意味着顏色可能稍微偏離一點,特別是在邊緣以及顏色從白色變爲另一種顏色的地方。尋找簡單的白色可能無法找到所有想要透明的像素。 – GolezTrol

+1

只是爲了完成這個答案:使用'imagesavealpha($ f,true);'確保alpha通道被保存並且'imagepng($ f,'/path/to/save/file.png');'保存爲PNG。 – megaflop

+0

更多詳情[here](http://www.php.net/manual/en/ref.image.php)。 – awm

-3

我發現這個解決方案在Convert jpg image to gif, png & bmp format using PHP

$imageObject = imagecreatefromjpeg($imageFile); 
imagegif($imageObject, $imageFile . '.gif'); 
imagepng($imageObject, $imageFile . '.png'); 
imagewbmp($imageObject, $imageFile . '.bmp'); 
+0

你還沒有回答透明度問題。 – megaflop

0

這爲我工作:

$image = imagecreatefromjpeg("image.jpg"); 
imagealphablending($image, true); 
imagepng($image, "image.png");