我正在尝试测试编写单个图像或压缩包是否更快。我的方法是创建一个 0 到 255(8 位图像)之间值的随机字节数组,并从中形成一个位图,使用 Bitmap.Save 重复写入。通过这种方式,我可以将 PixelFormat 设置为 Format8bppIndexed,从而提供灰度图像:
// Random number Generator
Random rnd = new Random();
// Create a single image
int Width = 640;
int Height = 512;
var b = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
ColorPalette ncp = b.Palette;
for (int i = 0; i < 256; i++)
ncp.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = ncp;
var BoundsRect = new Rectangle(0, 0, Width, Height);
BitmapData bmpData = b.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
b.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * b.Height;
var rgbValues = new byte[bytes];
// fill in rgbValues, e.g. with a for loop over an input array
rnd.NextBytes(rgbValues);
Marshal.Copy(rgbValues, 0, ptr, bytes);
b.UnlockBits(bmpData);
// copy image to a list of ~1000
List<Bitmap> bmps = new List<Bitmap>();
for (int i = 0; i < 500; i++)
bmps.Add(new Bitmap(b));
// Write to individual files
DateTime t0=DateTime.Now;
for (int i=0;i<bmps.Count;i++)
b.Save(@"C:\Temp\DiskTransferTest\IndividualImages\" + i.ToString() + ".bmp");
DateTime t1=DateTime.Now;
Console.WriteLine("Time to write individually: " + (t1-t0).ToString());
之后,我尝试将它们全部压缩到一个 ZIP 文件中并使用 DotNetZip 保存。这可行,但我得到的是彩色图像而不是灰度图像,因此文件大小要大得多。
// Create memorystreams from bitmap to pass to DotNetZip
List<MemoryStream> mss = new List<MemoryStream>();
for (int i = 0; i < bmps.Count; i++)
{
mss.Add(new MemoryStream());
bmps[i].Save(mss[i], ImageFormat.Bmp);
mss[i].Seek(0, SeekOrigin.Begin);
}
// Compress and write
t0 = DateTime.Now;
using (ZipFile zipfile = new ZipFile())
{
zipfile.CompressionLevel = 0;
int i=0;
foreach (MemoryStream ms in mss)
{
string pictureName = i.ToString() + ".bmp";
zipfile.AddEntry(pictureName,ms);
i++;
}
zipfile.Save(@"C:\Temp\DiskTransferTest\zipped.zip");
}
t1 = DateTime.Now;
Console.WriteLine("Time to write compressed: " + (t1 - t0).ToString());
关于如何通过 MemoryStream 将灰度写入 zip 的任何建议?