class Morandi::ImageBorder

Attributes

border_size[RW]
colour[RW]
crop[RW]
print_size[RW]
shrink[RW]
size[RW]
style[RW]

Public Class Methods

new(style='none', colour='white') click to toggle source
Calls superclass method Morandi::ImageOp::new
# File lib/morandi/image-ops.rb, line 158
def initialize(style='none', colour='white')
  super()
  @style = style
  @colour = colour
end

Public Instance Methods

call(image, pixbuf) click to toggle source
# File lib/morandi/image-ops.rb, line 164
def call(image, pixbuf)
  return pixbuf unless %w[square retro].include? @style
  surface = Cairo::ImageSurface.new(:rgb24, pixbuf.width, pixbuf.height)
  cr = Cairo::Context.new(surface)

  img_width = pixbuf.width
  img_height = pixbuf.height

  cr.save do
    if @crop
      if @crop[0] < 0 || @crop[1] < 0
        img_width = size[0]
        img_height = size[1]
        cr.translate( - @crop[0], - @crop[1])
      end
    end

    cr.save do
      cr.set_operator :source
      cr.set_source_rgb 1, 1, 1
      cr.paint

      cr.rectangle(0, 0, img_width, img_height)
      case colour
      when 'dominant'
        pixbuf.scale_max(400).save(fn="/tmp/hist-#{$$}.#{Time.now.to_i}", 'jpeg')
        hgram = Colorscore::Histogram.new(fn)
        File.unlink(fn) rescue nil
        col =  hgram.scores.first[1]
        cr.set_source_rgb col.red/256.0, col.green/256.0, col.blue/256.0
      when 'retro'
        cr.set_source_rgb 1, 1, 0.8
      when 'black'
        cr.set_source_rgb 0, 0, 0
      else
        cr.set_source_rgb 1, 1, 1
      end
      cr.fill
    end
  end

  border_scale =  [img_width,img_height].max.to_f / print_size.max.to_i
  size = @border_size
  size *= border_scale
  x, y = size, size

  # This biggest impact will be on the smallest side, so to avoid white
  # edges between photo and border scale by the longest changed side.
  longest_side = [pixbuf.width, pixbuf.height].max.to_f

  # Should be less than 1
  pb_scale = (longest_side - (size * 2)) / longest_side

  if @crop
    if @crop[0] < 0 || @crop[1] < 0
      x -= @crop[0]
      y -= @crop[1]
    end
  end

  case style
  when 'retro'
    # WARNING: CairoUtils class is not available in this gem!
    CairoUtils.rounded_rectangle(cr, x, y,
                                 img_width + x - (size*2), img_height+y-(size*2), size)
  when 'square'
      cr.rectangle(x, y, img_width - (size*2), img_height - (size*2))
  end
  cr.clip()

  if @shrink
    cr.translate(size, size)
    cr.scale(pb_scale, pb_scale)
  end
  cr.set_source_pixbuf(pixbuf)
  cr.rectangle(0, 0, pixbuf.width, pixbuf.height)

  cr.paint(1.0)
  final_pb = surface.to_pixbuf
  cr.destroy
  surface.destroy
  return final_pb
end