gpt4 book ai didi

arrays - 如何将 (StorableArray (Int, Int) Word8) 转换为惰性 ByteString?

转载 作者:行者123 更新时间:2023-12-04 14:06:47 24 4
gpt4 key购买 nike

我正在尝试加载 PNG 文件,获取未压缩的 RGBA 字节,然后将它们发送到 gzip 或 zlib 包。

pngload 包以 (StorableArray (Int, Int) Word8) 形式返回图像数据,压缩包采用惰性字节字符串。因此,我正在尝试构建一个 (StorableArray (Int, Int) Word8 -> ByteString) 函数。

到目前为止,我已经尝试了以下方法:

import qualified Codec.Image.PNG as PNG
import Control.Monad (mapM)
import Data.Array.Storable (withStorableArray)
import qualified Data.ByteString.Lazy as LB (ByteString, pack, take)
import Data.Word (Word8)
import Foreign (Ptr, peekByteOff)

main = do
-- Load PNG into "image"...
bytes <- withStorableArray
(PNG.imageData image)
(bytesFromPointer lengthOfImageData)

bytesFromPointer :: Int -> Ptr Word8 -> IO LB.ByteString
bytesFromPointer count pointer = LB.pack $
mapM (peekByteOff pointer) [0..(count-1)]

这会导致堆栈内存不足,所以很明显我做错了什么。我可以用 Ptr 和 ForeignPtr 尝试更多的东西,但是那里有很多“不安全”的功能。

任何帮助将不胜感激;我很困惑。

最佳答案

通常,打包和解包对于性能来说是个坏主意。如果你有一个 Ptr 和一个以字节为单位的长度,你可以通过两种不同的方式生成一个严格的字节串:

  • packCStringLen
  • unsafePackCStringLen

  • 像这样:
    import qualified Codec.Image.PNG as PNG
    import Control.Monad
    import Data.Array.Storable (withStorableArray)

    import Codec.Compression.GZip

    import qualified Data.ByteString.Lazy as L
    import qualified Data.ByteString.Unsafe as S

    import Data.Word
    import Foreign

    -- Pack a Ptr Word8 as a strict bytestring, then box it to a lazy one, very
    -- efficiently
    bytesFromPointer :: Int -> Ptr Word8 -> IO L.ByteString
    bytesFromPointer n ptr = do
    s <- S.unsafePackCStringLen (castPtr ptr, n)
    return $! L.fromChunks [s]

    -- Dummies, since they were not provided
    image = undefined
    lengthOfImageData = 10^3

    -- Load a PNG, and compress it, writing it back to disk
    main = do
    bytes <- withStorableArray
    (PNG.imageData image)
    (bytesFromPointer lengthOfImageData)
    L.writeFile "foo" . compress $ bytes

    我正在使用 O(1) 版本,它只是从 StorableArray 重新打包 Ptr。您可能希望先通过“packCStringLen”复制它。

    关于arrays - 如何将 (StorableArray (Int, Int) Word8) 转换为惰性 ByteString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3128046/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com