0

I am trying to convert all of the pngs in a folder to 8bpp pngs using nQuant. 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.

Is there anyway to read and write on the same FileStream?

I23BigC
  • 3
  • 5
  • do a quick google search on the following `C# Stackoverflow reading and writing to same FileStream` – MethodMan Feb 06 '17 at 22:20
  • @MethodMan Yes I found [this](http://stackoverflow.com/questions/605685/how-to-both-read-and-write-a-file-in-c-sharp) and I used the top answer. I also found [this](http://stackoverflow.com/questions/33633344/read-and-write-to-a-file-in-the-same-stream) and tried adding fs.Flush() but that also didn't work. – I23BigC Feb 06 '17 at 22:28

1 Answers1

1

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.

Uladzimir Palekh
  • 1,676
  • 10
  • 16