[Haskell-cafe] Right way to implement setPixel function

CK Kashyap ck_kashyap at yahoo.com
Thu Aug 20 02:32:18 EDT 2009


Hi,
I had posted a note on line drawing algo with Haskell some time back. Now, I am trying to write a PNM image.

import qualified Data.ByteString as B

width = 256
height = 256
bytesInImage = width * height * 3
blankImage =  B.pack $ take bytesInImage (repeat 0)

type Color = (Int,Int,Int)
setPixel :: B.ByteString -> Int -> Int -> Color -> B.ByteString
setPixel image x y (r,g,b) = B.concat [beforePixel, pixel, afterPixel]
        where
                beforePixel = B.take before image
                afterPixel = B.drop (before+3) image
                pixel=B.pack [(fromIntegral r),(fromIntegral g),(fromIntegral b)]
                -- number of bytes before the 3 bytes of
                -- the pixel at x y
                before = (y * width * 3) + (x * 3) - 3

main = do
        putStrLn "P6"
        putStrLn ( (show width) ++ " " ++ (show height) )
        putStrLn "255"
        -- Set a red pixel at 100 100
        B.putStr (setPixel blankImage 100 100 (255,0,0)) 


Can I please have some review comments on the code above? Would recreating the entire ByteString for each setPixel be an overhead?
Also, I am barely beginning to grasp the Monad concept....I was wondering if there could be a monadic style of implementation of this - that could potentially have a series of setPixels inside a do block?

Regards,
Kashyap



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090820/62977532/attachment.html


More information about the Haskell-Cafe mailing list