1

我正在尝试以下代码以压缩和保存屏幕截图的位图,但出现此错误。我没有尝试过使用 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

我看到文件已创建但已损坏。

4

1 回答 1

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);

执行后得到如下输出:

在此处输入图像描述

用 WinRar 打开文件并解压文件: 在此处输入图像描述

在文件夹中找到提取的图像:

在此处输入图像描述

更新: 我认为 OP 代码的唯一问题this.compressor是没有初始化。

于 2018-02-12T18:43:14.210 回答