class RemoveBg::ImageComposer

Combines alpha.png and color.jpg files to produce a full-sized transparent PNG. An image processing library (ImageMagick, GraphicsMagick, or libvips) must be available on the system. @see RemoveBg::CompositeResult

Constants

DEFAULT_BINARY_DETECTOR

Public Class Methods

detect_image_processor(detector: DEFAULT_BINARY_DETECTOR) click to toggle source
# File lib/remove_bg/image_composer.rb, line 14
def self.detect_image_processor(detector: DEFAULT_BINARY_DETECTOR)
  case
  when detector.call("magick"), detector.call("convert"), detector.call("gm")
    :minimagick
  when detector.call("vips")
    :vips
  end
end

Public Instance Methods

compose(color_file:, alpha_file:, destination_path:) click to toggle source
# File lib/remove_bg/image_composer.rb, line 23
def compose(color_file:, alpha_file:, destination_path:)
  image = case configured_image_processor
    when :vips
      then vips_compose(color_file: color_file, alpha_file: alpha_file)
    when :minimagick
      then minimagick_compose(color_file: color_file, alpha_file: alpha_file)
    when nil
      raise RemoveBg::Error, "Please configure an image processor to use image composition"
    else
      raise RemoveBg::Error, "Unsupported image processor: #{configured_image_processor.inspect}"
    end

  image.call(destination: destination_path)
end

Private Instance Methods

configured_image_processor() click to toggle source
# File lib/remove_bg/image_composer.rb, line 40
def configured_image_processor
  RemoveBg::Configuration.configuration.image_processor
end
minimagick_compose(color_file:, alpha_file:) click to toggle source
# File lib/remove_bg/image_composer.rb, line 44
def minimagick_compose(color_file:, alpha_file:)
  require "image_processing/mini_magick"

  ImageProcessing::MiniMagick
    .source(color_file)
    .composite(alpha_file, mode: "copy-opacity")
end
vips_compose(color_file:, alpha_file:) click to toggle source
# File lib/remove_bg/image_composer.rb, line 52
def vips_compose(color_file:, alpha_file:)
  require "image_processing/vips"

  ImageProcessing::Vips
    .source(color_file)
    .custom { |image| image.bandjoin(Vips::Image.new_from_file(alpha_file.path)) }
end