Permalink
Browse files

Add helper script for producing bitmaps.

  • Loading branch information...
lazyatom committed Jan 19, 2012
1 parent eed4f41 commit 346206de3d1c86a833a59462146090976f4b2a05
Showing with 37 additions and 0 deletions.
  1. +37 −0 image_to_bytes
View
@@ -0,0 +1,37 @@
+#!/usr/bin/env ruby
+
+=begin
+This script uses imagemagick and RMagick to produce a dithered version of an
+image, and then produces a cpp file containing an array of bytes suitable
+for printing.
+
+The cpp files also contain a comment which is useful to visualise the printed
+output; I suggest you open it in a text editor and shrink the fontsize until
+each row of characters fits on the screen without wrapping.
+=end
+
+require "rubygems"
+require "RMagick"
+include Magick
+
+path = ARGV[0]
+output_name = File.basename(path).split(".")[0...-1].join
+
+`convert -colorspace Gray -ordered-dither o2x2 #{path} #{output_name}.bmp`
+img = ImageList.new("#{output_name}.bmp")[0]
+bits = []
+img.each_pixel { |pixel, _, _| bits << (pixel.red > 0 ? 0 : 1) }
+bytes = []; bits.each_slice(8) { |s| bytes << ("0" + s.join).to_i(2).to_s(16) }
+File.open(output_name + ".cpp", "w") do |f|
+ f.puts "static unsigned char __attribute__ ((progmem)) image [] = {"
+ bytes.each_slice(img.columns / 8) { |slice| f.puts slice.map { |s| "0x"+s.rjust(2, "0") }.join(",") + ",//" }
+ f.puts "};"
+ f.puts
+ f.puts "/*"
+ bits.each_slice(img.columns) do |slice|
+ f.puts slice.map { |b| b == 0 ? "." : "X" }.join("")
+ end
+ f.puts "*/"
+end
+
+puts "wrote #{bytes.length} bytes to #{output_name}.cpp"

0 comments on commit 346206d

Please sign in to comment.