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

生成2.5GB/7000页TIFF子集时触发“数据处理溢出”异常求助

TIFF文件写入时的溢出异常问题

我有一个包含7000页的TIFF文件,每页图像尺寸为300×309像素,文件总大小为2.5GB。在WPF应用中可以正常读取并显示所有图像,但尝试生成图像子集的新TIFF文件时,系统抛出异常:The image data generated an overflow during processing(处理期间图像数据产生溢出)。

该异常仅在涉及第5789页及之后内容时触发:写入第1至5788页可正常运行,但从第5789页开始写入就会报错。

我已检查过显示设置,均为默认配置。

以下是读写TIFF文件的代码(基于.NET Framework 4.7.1):

Stream imageStreamSource = new FileStream(tiffFile, FileMode.Open, FileAccess.Read, FileShare.Read);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.None, BitmapCacheOption.Default);
var images = decoder.Frames.Cast<BitmapSource>().ToList().GetRange(5000, 1000);

using (var fs = new FileStream(saveTiffFile, FileMode.Create))
{
    BitmapEncoder encoder = new TiffBitmapEncoder();
    for (int i = 0; i < images.Count; i++)
    {
        encoder.Frames.Add(BitmapFrame.Create(images[i]));
    }
    encoder.Save(fs);
}

解决方案建议

  • 分批处理帧,减少内存占用
    当前代码一次性加载1000帧到内存,容易导致内存溢出。改为逐帧读取并分批写入,降低内存压力:
using (Stream imageStreamSource = new FileStream(tiffFile, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var fs = new FileStream(saveTiffFile, FileMode.Create))
{
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.None, BitmapCacheOption.Default);
    TiffBitmapEncoder encoder = new TiffBitmapEncoder();
    
    int startIndex = 5000;
    int count = 1000;
    int endIndex = Math.Min(startIndex + count, decoder.Frames.Count);

    for (int i = startIndex; i < endIndex; i++)
    {
        var frame = BitmapFrame.Create(decoder.Frames[i]);
        encoder.Frames.Add(frame);

        // 每100帧写入一次并重置编码器,防止内存累积
        if ((i - startIndex + 1) % 100 == 0)
        {
            encoder.Save(fs);
            encoder = new TiffBitmapEncoder();
        }
    }
    // 写入剩余未处理的帧
    if (encoder.Frames.Count > 0)
    {
        encoder.Save(fs);
    }
}
  • 修改TIFF压缩格式
    部分压缩格式在.NET Framework的TIFF编码器中存在处理限制,尝试切换为LZW或无压缩格式:
encoder.Compression = TiffCompressOption.Lzw;
// 或者使用无压缩
// encoder.Compression = TiffCompressOption.None;
  • 升级.NET Framework版本
    .NET Framework 4.7.1存在TIFF处理的已知溢出问题,升级到4.8及以上版本可能修复该bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:38:23