1

A user uploaded image file with handwriting in black ink. I want to remove the background and preserve the handwriting as a new .png image. Using Intervention Image there is a feature called trim() that sounds like it should do exactly this, but doesn't give the expected results.

Code:

$file = $request->file('employee_signature');

$name = $employee->givenname.'_'.$employee->surname.'_Signature.png';

$new_image = Intervention::make($file)->trim()->save('images/signatures/'.$name);

return $new_image;

$new_image should return an image called "First_Last_Signature.png" and only have the black handwriting. With my current code it doesn't trim the white background. I can confirm it's being processed because when I upload a .jpg it is saved as a .png in the specified directory.

There is a suggestion on GitHub that says the fill() should work, but I cannot get it to.

There is a solution here on SOF that does exactly what I want, but not using the Intervention Image library: LINK

I am currently using Imagemagick, however the GD library is available as well, although the Intervention Image docs do say that GD will use a lot of resources.

Community
  • 1
  • 1
Andrew Fox
  • 794
  • 4
  • 13
  • 30

3 Answers3

2

There is a solution, hope this helps:

$file = $request->file('employee_signature');

$name = $employee->givenname.'_'.$employee->surname.'_Signature.png';

$mask = Intervention::make($file)
    ->greyscale() // greyscale the signature image
    ->contrast(100) // increase the contrast to reach pure black and white
    ->contrast(50) // more contrast to ensure!
    ->trim('top-left', null, 40) // it's better to set a tolerance for trim()
    ->invert(); // invert it to use as a mask

$new_image = Intervention::canvas($mask->width(), $mask->height(), '#000000')
    ->mask($mask)
    ->save('images/signatures/'.$name);

return $new_image;
Stephan-v
  • 19,255
  • 31
  • 115
  • 201
Pourbahrami
  • 319
  • 1
  • 16
1

You may have luck using the transparent tool on LunaPic. You can simply click the background color you want removed and then further adjust the sharpness if needed. http://www167.lunapic.com/editor/?action=transparent

Kasper_Sky
  • 107
  • 1
  • 1
  • 3
0

ok, because i was using intevention 1.x and couldn't find a solution for my scaled jpg's i thought to post it hear now i finally did find a solution for the black background.

i found this code:

$img->fill('#ffffff', 0, 0); // flood fill image with color

For me it made the transparant surroundings, after zooming out, white instead of black.

I noticed it does not work 100% (sometimes to much white) but in most of the times it does. so maybe someone else needs this solution too.