2013-01-08 47 views
4

可能重複刪除的圖像白色背景色:
Translate Ruby into PHP code with the following code我們如何使用PHP代碼

我發現刪除的圖像白色背景彩色一個非常有用的Ruby代碼。

請參閱參考下面的代碼: Remove white background from an image and make it transparent

我試圖將代碼轉換爲PHP。但是,我收到了不想要的結果。這是我第一次在這裏發表問題,有人可以給我一些指導原則,並原諒我可憐的英語。

function setTransparency($new_image,$image_source) 
{   
    $transparencyIndex = imagecolortransparent($image_source); 
    $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255); 

    if ($transparencyIndex >= 0) { 
     $transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);  
    } 

    $transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']); 
    imagefill($new_image, 0, 0, $transparencyIndex); 
    imagecolortransparent($new_image, $transparencyIndex); 

} 

//create image from the source link 
$image = imagecreatefrompng('http://i.stack.imgur.com/k7E1F.png'); 

//create image mask layer 
$new_image = ImageCreateTruecolor(imagesx($image), imagesy($image)); 

//remove white background 
setTransparency($new_image,$image); 

//merge mask with original image source 
ImageCopyMerge($new_image, $image, 0, 0, 0, 0, imagesx($image), imagesy($image), 100); 

imagejpeg($new_image, null, 95); 
+0

您的鏈接引用了Mathematica解決方案,而不是Ruby。你會想看看使用ImageMagick:http://www.php.net/manual/en/book.imagick.php這是另一個包含ImageMagick解決方案的問題:http://stackoverflow.com/questions/7738437/rmagick-remove-white-background-from-image-and-make-it-transparent –

+0

這不是一個重複的問題,他想使用實際的php庫實現Mark Ransom的算法,你已經發布了一些命令行工具,它是根本不涉及Mark Ransom的算法 – user151496

回答

5

JPEG格式不支持透明度。你應該考慮使用png作爲輸出格式。將最後一行更改爲:

imagepng($new_image, null, 9);