不支持BitmapEncoder保存

问题描述 投票:0回答:1

我有以下代码,我看不出有什么问题,有什么想法可能是什么问题吗?

private static string SaveBaseImage( ZipArchive arc, DBImage image, int imageIndex )
{
    using (var mem = new MemoryStream(image.Data))
    {
        var bmp = BitmapFrame.Create(mem);
        //var bmp = BitmapFrame.Create(m‌​em, BitmapCreateOptions.‌​None, BitmapCacheOption.On‌​Load);
        var codex = bmp.Decoder.CodecInfo;

        var filename = $"{imageIndex}{codex.FileExtensions}";
        var imagezip = arc.CreateEntry(filename,CompressionLevel.Optimal));
        using (var imagestream = imagezip.Open())
        {
            SaveImage( bmp, imagestream);
        }
        return filename;
    }
}

private static void SaveImage(BitmapFrame data, Stream saveStream)
{
    var codex = data.Decoder.CodecInfo;
    var encoder = BitmapEncoder.Create(codex.ContainerFormat);
    encoder.Frames.Add(data);
    encoder.Save(saveStream);
}

当我运行时它会抛出

发生System.NotSupportedException HResult=-2146233067

Message=不支持指定的方法。来源=PresentationCore

堆栈跟踪: 在 System.Windows.Media.Imaging.BitmapEncoder.Save(流流) 在 FileFormatters.Export.SaveImage(BitmapFrame 数据,流 saveStream)

内部异常:null

MSDN 页面说

NotSupportedException:传递给编码器的 Frames 值为空。

NotSupportedException:帧计数小于或等于零。

但是帧数为 1 并且数据不为空

更多信息

arc declared as using (ZipArchive arc = new ZipArchive(stream, ZipArchiveMode.Create))
image.Data is byte[]
codex.FriendlyName = "PNG Decoder"
encoder.CodecInfo.FriendlyName = "PNG Encoder"
c# wpf c#-ziparchive bitmapencoder
1个回答
4
投票

似乎有必要将图像缓冲区写入中间 MemoryStream,然后才能将其写入 ZipEntry Stream:

private static void SaveImage(BitmapFrame data, Stream saveStream)
{
    var encoder = BitmapEncoder.Create(data.Decoder.CodecInfo.ContainerFormat);
    encoder.Frames.Add(data);

    using (var memoryStream = new MemoryStream())
    {
        encoder.Save(memoryStream);
        memoryStream.Position = 0;
        memoryStream.CopyTo(saveStream);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.