Created
July 11, 2012 22:08
-
-
Save lazyatom/3094035 to your computer and use it in GitHub Desktop.
Small script to convert an image to printer commands, based on http://github.com/freerange/printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# You should ensure that the `rmagick` and `a2_printer` gems are installed. | |
require "rubygems" | |
require "RMagick" | |
require "a2_printer" | |
if ARGV.length < 2 | |
puts "Usage: convert_image_to_bytes.rb <image_file> <output_file>" | |
exit -1 | |
end | |
image_file_name = ARGV[0] | |
output_file_name = ARGV[1] | |
# ========= | |
# | |
# Firstly, get the pixels from an image. | |
# This code is roughly based on https://github.com/freerange/printer/blob/master/lib/jobs/image_to_bits.rb | |
# Use Ruby's wrapper around the ImageMagick library to get the image data | |
img = Magick::ImageList.new(image_file_name)[0] | |
width = img.columns | |
height = img.rows | |
# Read the pixels into an array, determining which should be black using the | |
# pixel 'intensity'. | |
pixels = [] | |
white = (2**16)-1 | |
limit = white / 2 | |
img.each_pixel { |pixel, _, _| pixels << ((pixel.intensity < limit) ? 1 : 0) } | |
# ========== | |
# | |
# Next, convert that pixel array into the serial commands for a printer | |
# This code is roughly based on https://github.com/freerange/printer/blob/master/lib/print_processor/a2_raw.rb | |
printer_command_file = File.new(output_file_name, "w") # open the output file for writing | |
printer = A2Printer.new(printer_command_file) | |
# This roughly controls the darkness; for images with lots of black you will | |
# need to use less heat, otherwise I've found that the paper sticks. These little | |
# printers aren't great at printing lots and lots of black :-( | |
heat_time = 150 | |
# printer.begin(heat_time) | |
# Convert the pixels into bytes (groups of 8 pixels) | |
bytes = [] | |
pixels.each_slice(8) { |s| bytes << ("0" + s.join).to_i(2) } | |
# Use the A2Printer library to split the image data into chunks for us. | |
printer.print_bitmap(width, height, bytes) | |
# Feed enough paper to be able to nicely tear the paper | |
# printer.feed(3) | |
# Ensure that all the commands are written to the file, and close it. | |
printer_command_file.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment