Bitmap/Write a PPM file: Difference between revisions

Content added Content deleted
(Added Scheme)
Line 243: Line 243:
readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c)
readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c)
readNetpbm path = do
readNetpbm path = do
let die = fail "readImage: bad format"
h <- openFile path ReadMode
ppm <- readFile path
let die = hClose h >> fail "readImage: bad format"
ppm <- hGetContents h
let (s, rest) = splitAt 2 ppm
let (s, rest) = splitAt 2 ppm
unless (s == magicNumber) die
unless (s == magicNumber) die
Line 260: Line 259:
i <- stToIO $ listImage width height $
i <- stToIO $ listImage width height $
fromNetpbm $ map fromEnum rest
fromNetpbm $ map fromEnum rest
hClose h
return i
return i
where skipBlanks =
where skipBlanks =
Line 270: Line 268:


writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO ()
writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO ()
writeNetpbm path i = do
writeNetpbm path i = withFile path WriteMode $ \h -> do
h <- openFile path WriteMode
(width, height) <- stToIO $ dimensions i
(width, height) <- stToIO $ dimensions i
let w = hPutStrLn h
let w = hPutStrLn h
w $ magicNumber
w $ magicNumber
w $ show width ++ " " ++ show height
w $ show width ++ " " ++ show height
if null maxval
unless (null maxval) (w maxval)
then return ()
else w maxval
stToIO (getPixels i) >>= hPutStr h . toNetpbm
stToIO (getPixels i) >>= hPutStr h . toNetpbm
hClose h
where magicNumber = netpbmMagicNumber (nil :: c)
where magicNumber = netpbmMagicNumber (nil :: c)
maxval = netpbmMaxval (nil :: c)</lang>
maxval = netpbmMaxval (nil :: c)</lang>