4

Possible Duplicate:
Translate Ruby into PHP code with the following code

I found a very useful Ruby code on to remove image white background color.

Please see reference code below: Remove white background from an image and make it transparent

I tried to translate the code into php. However I am getting an unwanted result. This is my first time post question here, can someone please give me some guideline and forgive my poor English.

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('https://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);
Community
  • 1
  • 1
Jade
  • 41
  • 1
  • 3
  • Your link refers to a Mathematica solution, not Ruby. You'll want to look into using ImageMagick: http://www.php.net/manual/en/book.imagick.php Here is another question that includes an ImageMagick solution: http://stackoverflow.com/questions/7738437/rmagick-remove-white-background-from-image-and-make-it-transparent – Tony Zito Mar 20 '14 at 15:24
  • this is not a duplicate question, he wanted to implement Mark Ransom's algorithm using the actual php library, you've posted some commandline utility which is not related to Mark Ransom's algorithm at all – user151496 Oct 17 '16 at 15:42

1 Answers1

5

The JPEG format does not support transparency. You should consider to use png as output format. Change the last line to:

imagepng($new_image, null, 9);
hek2mgl
  • 152,036
  • 28
  • 249
  • 266