elixir-image/image

Trim by alpha

Closed this issue · 1 comments

I'm using chroma key to cut out pieces of clothing from their white background and I'd like to get rid of that transparent whitespace. Trim seems to be color based, but really I'd like to simply trim based on the alpha channel only.

Hey Benjamin, thanks for the issue. Should be very possible and I'll work on a background: :alpha option in my morning. If you're up for some experimentation it would be something like (not tested):

case  Image.split_alpha(image) do
  {_image, alpha} when !is_nil(alpha) ->
    # Find the trim area of the alpha band
    {:ok, {left, top, width, height}} = Vix.Vips.Operation.find_trim(alpha, background: [255,255,255], tolerance: 10.0)
    # Crop the image based upon the trim
    Image.crop(image, left, top, width, height)

  _other ->
    {:error, "Image has no alpha band"}
end

You might need to do some tuning on the find_trim/2 call for the tolerance. Let me know if that works (if you have time to experiment).