Skip to content

Instantly share code, notes, and snippets.

@larsch
Created July 17, 2016 06:42
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 larsch/0c53c679198ab118893f052b56890819 to your computer and use it in GitHub Desktop.
Save larsch/0c53c679198ab118893f052b56890819 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Convert .PNG to rasterized SVG for laster etching. Save PNG at 50.8
# DPI (2 lines per mm) or adjust 'dots_per_mm' below for different
# DPI. Horizontal resolution is also locked to this DPI in this
# version.
require 'chunky_png'
require 'nokogiri'
image = ChunkyPNG::Image.from_file(ARGV[0])
lines = []
image.height.times { |y|
line_start = nil
image.width.times { |x|
value = image[x, y]
if line_start && value > 128
# continue
elsif line_start
line_end = [x, y]
lines << [line_start, line_end]
line_start = nil
elsif value > 128
# begin line
line_start = [x, y]
end
}
if line_start
line_end = [image.width, y]
lines << [line_start, line_end]
end
}
dots_per_mm = 2.0
target_dpi = 90
mm_per_inch = 25.4
px_per_mm = target_dpi / mm_per_inch
scale = px_per_mm / dots_per_mm
builder = Nokogiri::XML::Builder.new do |xml|
xml.svg(xmlns: 'http://www.w3.org/2000/svg', version: '1.1') do
lines.each do |p1, p2|
xml.line(x1: p1[0] * scale,
y1: p1[1] * scale,
x2: p2[0] * scale,
y2: p2[1] * scale,
stroke: 'red', 'stroke-width' => 4)
end
end
end
puts builder.to_xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment