r/dailyprogrammer • • Jul 20 '12
[7/18/2012] Challenge #79 [intermediate] (Plain PGM file viewer)
Write a program that converts a "plain" .pgm file passed from stdin to an ASCII representation easily viewable in a terminal. If you're too lazy to read through the specification, the format should be simple enough to reverse-engineer from an example file:
P2
# feep.pgm
24 7
15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 3 3 3 3 0 0 7 7 7 7 0 0 11 11 11 11 0 0 15 15 15 15 0
0 3 0 0 0 0 0 7 0 0 0 0 0 11 0 0 0 0 0 15 0 0 15 0
0 3 3 3 0 0 0 7 7 7 0 0 0 11 11 11 0 0 0 15 15 15 15 0
0 3 0 0 0 0 0 7 0 0 0 0 0 11 0 0 0 0 0 15 0 0 0 0
0 3 0 0 0 0 0 7 7 7 7 0 0 11 11 11 11 0 0 15 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- The top line,
P2, is there to identify the file as a plain .pgm file. - Lines with a # in front of them are comments, and should be ignored.
- The first two numbers in the file are the width and height.
- The third number, 15 here, is the maximum grayscale value in the image: here, this means 15 is full white, and lower numbers are darker, 0 being pure black.
- Thereafter, a (width x height) grid specifying the image itself follows.
Your program should use ASCII symbols to represent different grayscale values. Assuming the text is black on a white background, you could use a gradient like this one:
" .:;+=%$#"
Converted, the example image would look something like this:
.... ;;;; ==== ####
. ; = # #
... ;;; === ####
. ; = #
. ;;;; ==== #
9
Upvotes
13
u/skeeto -9 8 Jul 20 '12 edited Jul 20 '12
I decided to do actual color output for mine. :-)
And the result screenshot: feep.png
(Edit: and bonus: reddit.png)
1
u/goldjerrygold_cs Jul 20 '12 edited Jul 21 '12
In c. Having a bit of trouble formatting the output.
Edited to reflect nooodl's tip. Thanks, worked like a charm!
2
u/lawlrng 0 1 Jul 20 '12
Output is:
2
u/5outh 1 0 Jul 20 '12 edited Jul 20 '12
Assuming that the numbers and header always span those same three lines, this works (with your gradient):
dp79Intermediate.exe feep.pgm yields:
1
u/ander1dw Jul 20 '12
Java:
Usage:
Output:
1
u/brenny87 Jul 21 '12
C# (script)
Output is:
1
u/[deleted] Jul 23 '12
A somewhat crufty C answer.
1
u/Uristqwerty Jul 24 '12
output
With a fancier image (scaled 3x, 2y, background replaced with a gradient)
Earlier, I used a windows-specific function for colors, which allowed the brighter 8 to be used as the background color:
Combined with extended ASCII, gives this.
(Order was actually reversed, as I only considered that the fancier characters might not be interpreted as pure ASCII afterwards, and later that an arbitrary terminal might not support the full range of background colors, and probably wouldn't be running a microsoft OS, either. And then, moments ago, I tossed in the original size version just for comparison. Somewhere in the middle, there was also this.)