2017-02-06 32 views
0

我试图用nQuant将文件夹中的所有pngs转换为8bpp png。我试着用下面的代码:在同一个FileStream上读写

foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly)) 
     { 
      using (MemoryStream memory = new MemoryStream()) 
      { 
       using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
       { 
        using (Bitmap image = new Bitmap(fs)) 
        { 
         using (Image quantized = quantizer.QuantizeImage(image)) 
         { 
          quantized.Save(memory, ImageFormat.Png); 
          byte[] bytes = memory.ToArray(); 
          fs.Write(bytes, 0, bytes.Length); 
         } 
        } 
       } 
      } 
     } 

然而,这是行不通的。没有例外。只是不写入文件。我用这个工作代码取代了它。

Bitmap image; 
foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly)) 
     { 
      using (FileStream fso = new FileStream(file, FileMode.Open, FileAccess.ReadWrite)) 
      { 
       image = new Bitmap(fso); 
      } 

      using (MemoryStream memory = new MemoryStream()) 
      { 
       using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite)) 
       { 
        using (Image quantized = quantizer.QuantizeImage(image)) 
        { 
         quantized.Save(memory, ImageFormat.Png); 
         byte[] bytes = memory.ToArray(); 
         fs.Write(bytes, 0, bytes.Length); 
        } 
       } 
      } 
     } 

好像FileMode.OpenOrCreate可以做一个或另一个,但不是两个。

无论如何读取和写在同一FileStream

+0

做一个快速的谷歌搜索下面的'C#Stackoverflow阅读和写入相同的FileStream' – MethodMan

+0

@MethodMan是的我发现[this](http://stackoverflow.com/questions/605685/how-to-both-read并且写入一个c-sharp文件),我使用了最上面的答案。我也发现[这](http://stackoverflow.com/questions/33633344/read-and-write-to-a-file-in-the-same-stream)并尝试添加fs.Flush(),但也是没有工作。 – I23BigC

回答

1

您的代码只是将这些图像的内容连接到一个文件,因为您没有重置文件流中的位置。

但是使用一个流是不好主意。如果您的新文件比旧文件小,则您的结果将被破坏,因为文件不会被调整为较小的大小。

改为使用临时文件。