我正在尝试使用以下代码来压缩和保存屏幕截图的位图但是会出现此错误。我没有尝试使用CompressFiles,因为我必须使用内存流。
public void CompressAndSaveBitmap(Bitmap bitmap)
{
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream file = new FileStream("XYZ", FileMode.Create, System.IO.FileAccess.Write))
{
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
// tried these but they don't work.
//memStream.Seek(0, 0);
//memStream.Position = 0;
this.compressor.CompressStream(memStream, file); // throws error here
// also tried the following to see if Bitmap contains the problem
//UnicodeEncoding uniEncoding = new UnicodeEncoding();
//byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");
//int count = 0;
//while (count < firstString.Length)
//memStream.WriteByte(firstString[count++]);
//memStream.Flush();
////memStream.Seek(0, 0);
//memStream.Position = 0;
//this.compressor.CompressStream(memStream, file);
}
}
}
压缩器初始化代码:
public Compressor()
{
SevenZipCompressor.SetLibraryPath(@"D:\7z.dll");
this.compressor = new SevenZip.SevenZipCompressor();
compressor.CompressionLevel = CompressionLevel.Ultra;
compressor.CompressionMethod = CompressionMethod.Ppmd;
}
它在图书馆的这一行崩溃了:
var lockObject = (object) _files ?? _streams;
lock (lockObject) // here in ArchiveUpdateCallback.cs
我看到文件已创建,但已损坏。
答案 0 :(得分:2)
我能够使用以下代码成功压缩文件:
public void CompressAndSaveBitmap(Bitmap bitmap)
{
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream file = new FileStream("XYZ", FileMode.Create, System.IO.FileAccess.Write))
{
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
// tried these but they don't work.
//memStream.Seek(0, 0);
//memStream.Position = 0;
SevenZipCompressor compressor =
new SevenZipCompressor
{
CompressionLevel = CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
compressor.CompressStream(memStream, file); // throws error here
}
}
}
以下是位图文件:
执行代码:
Bitmap bmp = new Bitmap("Test.bmp");
res.CompressAndSaveBitmap(bmp);
执行后得到以下输出:
在文件夹中找到提取的图像:
<强>更新强>
我认为OP代码的唯一问题是this.compressor
未初始化。