module Hakyll.Images.Common ( Image
, Image_(..)
, ImageFormat(..)
, format
, image
, loadImage
, encode
) where
import Prelude hiding (readFile)
import Codec.Picture.Types (DynamicImage)
import Codec.Picture.Saving
import Data.ByteString.Lazy (toStrict)
import Data.ByteString (ByteString)
import Hakyll.Core.Compiler (Compiler, getResourceLBS, getUnderlyingExtension)
import Hakyll.Core.Item (Item(..))
data ImageFormat
= Jpeg
| Png
| Bitmap
| Tiff
deriving (Eq)
data Image_ a = Image ImageFormat a
instance Functor Image_ where
fmap f (Image fmt a) = Image fmt (f a)
type Image = Image_ ByteString
format :: Image_ a -> ImageFormat
format (Image fmt _) = fmt
image :: Image_ a -> a
image (Image _ im) = im
loadImage :: Compiler (Item Image)
loadImage = do
content <- fmap toStrict <$> getResourceLBS
fmt <- fromExt <$> getUnderlyingExtension
return $ (Image fmt) <$> content
fromExt :: String -> ImageFormat
fromExt ".jpeg" = Jpeg
fromExt ".jpg" = Jpeg
fromExt ".png" = Png
fromExt ".bmp" = Bitmap
fromExt ".tif" = Tiff
fromExt ".tiff" = Tiff
fromExt ext = error $ "Unsupported format: " <> ext
encode :: ImageFormat -> DynamicImage -> Image
encode Jpeg im = Image Jpeg $ (toStrict . imageToJpg 100) im
encode Png im = Image Png $ (toStrict . imageToPng) im
encode Bitmap im = Image Bitmap $ (toStrict . imageToBitmap) im
encode Tiff im = Image Tiff $ (toStrict . imageToTiff) im