You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请教Haskell中HIP库decode函数第一个参数的用法及示例

如何使用HIP库的decode函数

decode的第一个参数是图像格式的标记实例——HIP库为每种支持的图像格式(如PNG、JPEG、BMP等)都定义了对应ImageFormat类型的实例值,用来明确告诉函数要解码哪种格式的字节流。

示例1:解码PNG格式文件

import qualified Data.ByteString as B
import Graphics.Image.IO.Formats (PNG(..), decode)
import Graphics.Image (Image, RGB)

-- 读取本地PNG文件并解码为RGB图像
decodePNGFile :: FilePath -> IO (Either String (Image RGB Word8))
decodePNGFile path = do
  fileBytes <- B.readFile path
  return $ decode PNG fileBytes

这里PNG()就是传给decode的第一个参数,它是PNG格式对应的ImageFormat实例构造器。

示例2:解码JPEG格式文件

import qualified Data.ByteString as B
import Graphics.Image.IO.Formats (JPG(..), decode)
import Graphics.Image (Image, YCbCr)

-- 读取本地JPG文件并解码为YCbCr图像
decodeJPGFile :: FilePath -> IO (Either String (Image YCbCr Word8))
decodeJPGFile path = do
  fileBytes <- B.readFile path
  return $ decode JPG fileBytes

同理,JPG()是JPEG格式的标记实例,其他格式如BMP、GIF分别对应BMP()、GIF()构造器。

关键提示

  • decode返回Either String img:解码成功时返回Right包裹的图像对象,失败时返回Left包裹的错误描述字符串。
  • 图像类型(如Image RGB Word8)需要和目标格式的默认色彩空间匹配,也可通过类型注解指定所需的色彩格式。

内容的提问来源于stack exchange,提问作者Refael Sheinker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:23:09