Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Peter Cooperx http://www.petercooper.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Patchwork quilt pattern in Ruby (from Knuth TAoCP 4 - 7.1.3)

In Donald Knuth's TAoCP Pre-Fascicle 1a: Bitwise Tricks and Techniques, he shows a patchwork quilt defined by f(x, y) = ((x ^ y) & ((y - 350) >> 3)) ** 2, designed by D. Sleator in 1976. I wanted to recreate this quilt myself using Ruby. The following program generates a PNG file of the "quilt."

   1  
   2  require 'rubygems'
   3  require 'png'
   4  
   5  def f(x, y)
   6    ( (x ^ y) & ((y - 350) >> 3) ) ** 2
   7  end
   8  
   9  canvas = PNG::Canvas.new(500, 500)
  10  
  11  0.upto(499) do |y|
  12    0.upto(499) do |x|
  13      canvas[x, 499 - y] = ((f(x, y) >> 12) & 1) == 1 ? PNG::Color::Black : PNG::Color::White
  14    end
  15  end
  16  
  17  png = PNG.new(canvas)
  18  png.save 'pattern.png'

Installing libjpeg on OS X

Get http://www.ijg.org/files/jpegsrc.v6b.tar.gz, and then:

   1  tar zxvf jpegsrc.v6b.tar.gz
   2  cd jpeg-6b
   3  cp /usr/share/libtool/config.sub .
   4  cp /usr/share/libtool/config.guess .
   5  ./configure --enable-shared --enable-static
   6  make
   7  sudo make install
   8  sudo ranlib /usr/local/lib/libjpeg.a

Thumbnailer in Ruby and RMagick

   1  require 'RMagick'
   2  
   3  maxwidth = 120
   4  maxheight = 160
   5  aspectratio = maxwidth.to_f / maxheight.to_f
   6  imgfile = 'world'
   7  
   8  pic = Magick::Image.read(imgfile + '.jpg').first
   9  imgwidth = pic.columns
  10  imgheight = pic.rows
  11  imgratio = imgwidth.to_f / imgheight.to_f
  12  imgratio > aspectratio ? scaleratio = maxwidth.to_f / imgwidth : scaleratio = maxheight.to_f / imgheight
  13  thumb = pic.resize(scaleratio)
  14  
  15  white_bg = Magick::Image.new(maxwidth, thumb.height)
  16  pic = white_bg.composite(thumb, Magick::CenterGravity, Magick::OverCompositeOp)
  17  pic.write(imgfile + '.thumb.jpg')
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS