1 ! Copyright (C) 2010 Erik Charlebois.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors ascii combinators images images.loader io
4 io.encodings.ascii io.encodings.string io.streams.throwing
5 kernel make math math.parser sequences ;
9 "ppm" ppm-image ?register-image-class
11 : read-token ( -- token )
15 [ "\n" read-until 2drop t ]
19 " \n\r\t" read-until drop swap
22 : read-number ( -- number )
23 read-token string>number ;
25 :: read-numbers ( n lim -- )
28 n 1 + lim read-numbers
31 :: read-ppm ( -- image )
36 width height 3 * * :> npixels
38 { "P3" [ [ 0 npixels read-numbers ] B{ } make ] }
39 { "P6" [ npixels read ] }
44 { width height } >>dim
47 ubyte-components >>component-type ;
49 M: ppm-image stream>image*
50 drop [ [ read-ppm ] throw-on-eof ] with-input-stream ;
52 M: ppm-image image>stream
54 [ drop "P6\n" ascii encode write ]
55 [ dim>> first number>string " " append ascii encode write ]
56 [ dim>> second number>string "\n" append ascii encode write ]
57 [ drop "255\n" ascii encode write ]