[Haskell-cafe] Right way to implement setPixel function
ck_kashyap at yahoo.com
Thu Aug 20 02:32:18 EDT 2009
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]
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 ( (show width) ++ " " ++ (show height) )
-- 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?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe