[Haskell] image writing library

Glynn Clements glynn.clements at virgin.net
Fri Aug 6 12:21:54 EDT 2004


Ketil Malde wrote:

> I discovered that although XPM accepts values in the range 0x00..0xff,
> it is still monochrome.  XGM (plain, that is, not raw) is
> approximately the same format, but displays the way I wanted.  So I
> ended up using:
> 
>     mkpgm :: Array (Int,Int) Int -> String
>     mkpgm cm = header ++ "\n" ++ image
>         where header = unwords ["P2",show width,show heigth,show maxval]

This may not work for many programs which read PGM files. The header
is usually split into multiple lines, e.g.

	P2
	256 256
	255

Some programs may accept arbitrary whitespace between tokens, but
others may insist upon newlines, e.g.:

    mkpgm cm = header ++ image
        where header = unlines $ map unwords [["P2"],[show width, show height],[show maxval]]

Also:

>               (width,heigth) = snd $ bounds cm

This assumes that "fst $ bounds cm == (1,1)".

> Not *very* beautiful, but seems to do the job for my stuff.  I'll try
> the PPM library if I need something a tad more fancy - like colors :-)

Writing PPM is only marginally more complex, e.g.:

    mkppm :: Array (Int,Int) (Int, Int, Int) -> String
    mkppm cm = header ++ image
        where header = unlines $ map unwords [["P3"],[show width, show height],[show maxval]]
              image = unlines $ map showRGB $ elems cm
              width = x1 - x0 + 1
              height = y1 - y0 + 1
              ((x0,y0),(x1,y1)) = bounds cm
              maxval = maximum $ concatMap unRGB (elems cm)
              showRGB (r,g,b) = unwords [show r, show g, show b]
              unRGB (r,g,b) = [r,g,b]

-- 
Glynn Clements <glynn.clements at virgin.net>


More information about the Haskell mailing list