Skip to content

Instantly share code, notes, and snippets.

@mxrguspxrt
Created November 24, 2011 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxrguspxrt/1392224 to your computer and use it in GitHub Desktop.
Save mxrguspxrt/1392224 to your computer and use it in GitHub Desktop.
autocrop, colorize, solid color
# Usage:
#
# image1 = ChunkyPNG::Image.from_file('vase.png')
# image1.colorfy!(:color => "ff0000")
# image1.save 'changed_red.png'
#
# image2 = ChunkyPNG::Image.from_file('vase.png')
# image2.colorfy!(:color => "ff0000", :solid => true)
# image2.save 'only_red.png'
#
#
# @author Margus Pärt
# @version 24.11.2011
module ChunkyPNG
module Color
# Replace color with choosed color, depending on options
#
#
# Options:
# => string|Color :color new color
# => boolean :solid if set to solid, only orginal picture alpha is
def colorfy(pixel, options)
n = ChunkyPNG.Color(options[:color])
if options[:solid]
r = r(n)
g = g(n)
b = b(n)
else
gs = grayscale_teint(pixel)
gf = gs / 255.0
r = gf * r(n)
g = gf * g(n)
b = gf * b(n)
end
ChunkyPNG::Color::rgba(r.to_i, g.to_i, b.to_i, a(pixel))
end
end
class Canvas
# Replace canvas colors with one color level
#
# Options:
# => :color
# => :solid
def colorfy!(options = {})
pixels.map! { |pixel| Color.colorfy(pixel, options) }
end
# Get pixel addresses of color
#
# @arg int|string With color ff0000 format
# @returns array [[pixel1_x, pixel1_y], [pixel2_x, pixel2_y]]
def get_color_pixel_cordinates(c)
c = c.downcase
cords = []
# get_pixel, width and height are Canvas methods
for i in 0...width
for j in 0...height
cords << [i,j] if (Color.to_hex(get_pixel(i, j), false) == "##{c}")
end
end
cords
end
# Autocrop transparent pixels
def autocrop!
# mark where pixel found (relative to point 0, 0)
e = {:top=>false, :bottom=>false, :left=>false, :right=>false}
# find real picture cordinates (exclude transparent)
for x in 0...width
for y in 0...height
# found color
if 254 < Color.a(get_pixel(x, y))
# mark it not to be cropped
e[:top] = y if not e[:top] or y < e[:top]
e[:bottom] = y if not e[:bottom] or y > e[:bottom]
e[:left] = x if not e[:left] or x < e[:left]
e[:right] = x if not e[:right] or x > e[:right]
end
end
end
# crooooop
crop!(e[:left], e[:top], e[:right]-e[:left], e[:bottom]-e[:top])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment