简体   繁体   English

在同一FileStream上读写

[英]Reading and Writing on same FileStream

I am trying to convert all of the pngs in a folder to 8bpp pngs using nQuant . 我正在尝试使用nQuant将文件夹中的所有png转换为8bpp png I tried using the following code: 我尝试使用以下代码:

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

This however, doesn't work. 但是,这不起作用。 No exceptions. 没有例外。 Just simply doesn't write to the file. 只是根本不写入文件。 I've replaced it with this working code. 我已用此工作代码替换了它。

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

Seems like FileMode.OpenOrCreate can do one OR the other, but not both. 好像FileMode.OpenOrCreate可以做一个或另一个,但不能两者都做。

Is there anyway to read and write on the same FileStream ? 无论如何,在同一个FileStream上可以读写?

Your code just concatenates content of these images to one file as you are not resetting position in the file stream. 您的代码只是将这些图像的内容连接到一个文件中,因为您没有重置文件流中的位置。

But it is bad idea to use one stream. 但是使用一个流是个坏主意。 If your new file is smaller than old, your result will be broken as file will not be resized to smaller size. 如果新文件小于旧文件,则结果将被破坏,因为文件不会被调整为较小的尺寸。

Use temp files instead. 请改用临时文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM