|Problems? Is your data what you think it is?|
Re: PNG to ASCII ?by jimt (Chaplain)
|on Oct 16, 2006 at 21:26 UTC||Need Help??|
I would do it thusly:
But I may have misunderstood the question. ;-)
Update: As per request by muba below, I'll explain the logic, at least roughly. This is a trimmed down version of a much more sophisticated ascii art generator I developed a few years ago. I then lost the code, I thought forever. I was sad. Then, about 2 months ago, I re-discovered it. It was in a folder called "misc" on a burned cd labeled "misc". I've been working on modernizing and cleaning it up, and when I'm done I'll probably place on CPAN. My home node pic was done with that version of the software.
Anyway, in the trimmed down version here, the logic is pretty easy. Think of a character as a bitmapped image. The text is black, the rest is white. I did this with all the printable ascii characters. From there, just arrange them from darkest -> lightest. There are something like 100 printable characters, which makes for a pretty noisy image. I've had fabulous results by scaling down to only the 5 lightest and 5 darkests. That's that @master_ascii list up at the top.
Ordering the characters is the toughest part. From there, it's easy. Use GD to read in the PNG pixel by pixel and stuff the image into an array of arrayrefs. Each offset in the array corresponds to a pixel. So $matrix->-> is pixel 0,0 in the image file and so on (but note - the matrix is in printable order, so the coordinates are actually (y,x). At each spot, store the grayscale value of the pixel, which we get by just averaging together the RGB values.
Next, just loop through that data structure. At each point, we have a numeric value. Covert it into an offset into our @master_ascii array, and then print out that character. I think it'd work w/o that if/ladder to explicitly set the 0 and 255 values, but I had those there for a reason at some point and just left it.
Easy as pie.
Update 2: Incorporated ikegami's suggestions and re-inserted the code to help preserve aspect ratio (as I'd said, this code had been greatly simplified, so it was easy to add back in, but it's still the older stuff I haven't tidied up yet). Past experimentation yielded that a 2/3 ratio seemed to be the best. Note - I left the @master_ascii definition as is, since compressing it all into a single qw() list throws warning about the comma.