From: Harold Hausman Date: 2005-10-12T10:23:09+09:00 Subject: Re: [QUIZ] [Solution] Text Image (#50) ------=_Part_4998_28661170.1129080179787 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline Hi, Best quiz yet. Er, well, quiz which held my attention longest anyway. :) My solution is um, less... elegant, than some of the others, but in a lot o= f ways, like a parent who mistakenly thinks their ugly child is cute I kinda like it. I don't really share my code a lot (maybe for obvious reasons) but I'm just so pleased with how easily ruby lets me hack things to high heaven and this one in particular makes me smile. Take special note that it only works on 24 bit .bmp files and put your hard hat on if you think you're going to feed anything but that into it. ;) Okay, enough blather, without further ado, the first code I've shared with you guys: #It only supports 24bit bmp files, and it even chokes on most of them ;) #It creates one character per pixel (which has obvious implications) #But it's 40 lines of pure ruby no lib use binary file up-hackery... #And quite frankly, thats what I do. MyPixel =3D Struct.new( 'MyPixel', :r, :g, :b ) the_gradient =3D %w|D Y 8 S 6 5 J j t c + i ! ; : .| ###############PUT YOUR FILENAME HERE######################################### the_file =3D File.new('ducky.bmp', 'rb') the_file.read(2) #BM the_file.read(4).unpack('V')[0] #filesize the_file.read(4) #unused the_file.read(4).unpack('V')[0] #offset from beginning to bitmap data the_file.read(4).unpack('V')[0] #size of bitmap header image_x =3D the_file.read(4).unpack('V')[0] #width x in pixels image_y =3D the_file.read(4).unpack('V')[0] #height y in pixels the_file.read(2).unpack('v')[0] #planes? the_file.read(2).unpack('v')[0] #bits per pixel the_file.read(24) #unused the_bitmap =3D [] puts "CRRRRUNCHHHH --- please wait, reading file..." image_y.times do |row| the_bitmap[row] =3D [] image_x.times do |col| the_bitmap[row][col] =3D MyPixel.new( 0, 0, 0 ) the_bitmap[row][col].b =3D the_file.read(1).unpack('c')[0] the_bitmap[row][col].g =3D the_file.read(1).unpack('c')[0] the_bitmap[row][col].r =3D the_file.read(1).unpack('c')[0] end end puts "output coming:" the_output =3D File.new('output.asciiart', 'w') (image_y-1).downto(0) do |row| image_x.times do |col| the_avg =3D (the_bitmap[row][col].b+the_bitmap[row][col].g+the_bitmap[row][col].r)/3 the_output.write(the_gradient[the_avg>>4]) end the_output.write("\n") end ------=_Part_4998_28661170.1129080179787--