1 ! Copyright (C) 2010 Erik Charlebois.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types ascii combinators images
4 images.loader io io.encodings.ascii io.encodings.string
5 io.streams.throwing kernel make math math.parser sequences
7 SPECIALIZED-ARRAY: ushort
11 "pgm" pgm-image ?register-image-class
13 : read-token ( -- token )
17 [ "\n" read-until 2drop t ]
21 " \n\r\t" read-until drop swap
24 : read-number ( -- number )
25 read-token string>number ;
27 :: read-numbers ( n lim -- )
30 n 1 + lim read-numbers
33 :: read-pgm ( -- image )
38 width height * :> npixels
42 { "P2" [ [ 0 npixels read-numbers ] wide [ ushort-array{ } ] [ B{ } ] if make ] }
43 { "P5" [ wide [ 2 ] [ 1 ] if npixels * read ] }
48 { width height } >>dim
51 wide [ ushort-components ] [ ubyte-components ] if >>component-type ;
53 M: pgm-image stream>image*
54 drop [ [ read-pgm ] throw-on-eof ] with-input-stream ;
56 M: pgm-image image>stream
58 [ drop "P5\n" ascii encode write ]
59 [ dim>> first number>string " " append ascii encode write ]
60 [ dim>> second number>string "\n" append ascii encode write ]
61 [ component-type>> ubyte-components = [ "255\n" ] [ "65535\n" ] if ascii encode write ]