1 ! Copyright (C) 2010 Erik Charlebois.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types ascii combinators images images.loader
4 io io.encodings.ascii io.encodings.string kernel locals make math
5 math.parser sequences specialized-arrays io.streams.throwing ;
6 SPECIALIZED-ARRAY: ushort
10 "pgm" pgm-image ?register-image-class
12 : read-token ( -- token )
16 [ "\n" read-until 2drop t ]
20 " \n\r\t" read-until drop swap
23 : read-number ( -- number )
24 read-token string>number ;
26 :: read-numbers ( n lim -- )
29 n 1 + lim read-numbers
32 :: read-pgm ( -- image )
37 width height * :> npixels
41 { "P2" [ [ 0 npixels read-numbers ] wide [ ushort-array{ } ] [ B{ } ] if make ] }
42 { "P5" [ wide [ 2 ] [ 1 ] if npixels * read ] }
47 { width height } >>dim
50 wide [ ushort-components ] [ ubyte-components ] if >>component-type ;
52 M: pgm-image stream>image*
53 drop [ [ read-pgm ] throw-on-eof ] with-input-stream ;
55 M: pgm-image image>stream
57 [ drop "P5\n" ascii encode write ]
58 [ dim>> first number>string " " append ascii encode write ]
59 [ dim>> second number>string "\n" append ascii encode write ]
60 [ component-type>> ubyte-components = [ "255\n" ] [ "65535\n" ] if ascii encode write ]