.NET GDI +图像大小 - 文件编解码器限制

6 .net gdi+ codec

是否可以使用.NET提供的图像文件编解码器编码的图像大小有限制?

我正在尝试编码大小为4GB的图像,但它根本无法正常工作(或无法正常工作,即写出不可读的文件).bmp,.jpg,.png或.tif编码器.

当我将图像大小降低到<2GB时,它确实适用于.jpg而不是.bmp,.tif或.png.

我的下一次尝试是尝试libtiff,因为我知道tiff文件适用于大图像.

什么是大图像的良好文件格式?或者我只是达到文件格式限制?

(所有这些都是在具有8 GB RAM的64位操作系统(WinXP 64)上完成的,并使用x64架构进行编译.)

Random r = new Random((int)DateTime.Now.Ticks);

int width = 64000;
int height = 64000;
int stride = (width % 4) > 0 ? width + (width % 4) : width;
UIntPtr dataSize = new UIntPtr((ulong)stride * (ulong)height);
IntPtr p = Program.VirtualAlloc(IntPtr.Zero, dataSize, Program.AllocationType.COMMIT | Program.AllocationType.RESERVE, Program.MemoryProtection.READWRITE);

Bitmap bmp = new Bitmap(width, height, stride, PixelFormat.Format8bppIndexed, p);
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);

ColorPalette cp = bmp.Palette;
for (int i = 0; i < cp.Entries.Length; i++)
{
  cp.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = cp;

unsafe
{
  for (int y = 0; y < bd.Height; y++)
  {
    byte* row = (byte*)bd.Scan0.ToPointer() + (y * bd.Stride);
    for (int x = 0; x < bd.Width; x++)
    {
      *(row + x) = (byte)r.Next(256);
    }
  }
}

bmp.UnlockBits(bd);
bmp.Save(@"c:\test.jpg", ImageFormat.Jpeg);
bmp.Dispose();

Program.VirtualFree(p, UIntPtr.Zero, 0x8000);
Run Code Online (Sandbox Code Playgroud)

我也尝试使用固定的GC内存区域,但这仅限于<2GB.

Random r = new Random((int)DateTime.Now.Ticks);

int bytesPerPixel = 4;
int width = 4000;
int height = 4000;         
int padding = 4 - ((width * bytesPerPixel) % 4);
padding = (padding == 4 ? 0 : padding);
int stride = (width * bytesPerPixel) + padding;
UInt32[] pixels = new UInt32[width * height];
GCHandle gchPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
using (Bitmap bmp = new Bitmap(width, height, stride, PixelFormat.Format32bppPArgb, gchPixels.AddrOfPinnedObject()))
{
    for (int y = 0; y < height; y++)
    {
        int row = (y * width);
        for (int x = 0; x < width; x++)
        {
            pixels[row + x] = (uint)r.Next();
        }
    }

    bmp.Save(@"c:\test.jpg", ImageFormat.Jpeg);
}
gchPixels.Free();
Run Code Online (Sandbox Code Playgroud)

Chr*_*heD 2

您面临的问题很可能是 .NET Framework 中的以下限制:GC 堆中允许的最大对象大小为 2GB,即使在 64 位操作系统/版本上也是如此。

一些参考:链接链接链接

根据您的需要,使用相对简单(未压缩)的格式(例如 TIFF),可以分部分生成图像并随后合并这些部分。只是一个想法..