none
A bug in BmpBitmapEncoder RRS feed

  • Question

  • I think I found a bug in BmpBitmapEncoder. Here is a code snippet:

                    var data = File.ReadAllBytes("data.raw");
    
                    BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
                    bitmapEncoder = new PngBitmapEncoder
                    {
                        Interlace = PngInterlaceOption.Off
                    };
                    using (var output = new MemoryStream())
                    {
                        var bitmapSource = BitmapSource.Create(1600, 1000,
                            96, 96, PixelFormats.Gray8, null, data, 1600);
                        bitmapSource.Freeze();
                        bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    
                        bitmapEncoder.Save(output);
    
                        var png = new byte[output.Position];
                        Array.Copy(output.GetBuffer(), png, output.Position);
    
                        File.WriteAllBytes(fileName + ".png", png);
                    }
    

    There is a specific "data.raw" file that produces correct picture with PngBitmapEncoder, but with BmpBitmapEncoder it produces an incomplete result. Exact same data file. I could attach the raw file or send it over for evaluation upon request.

    Saturday, January 12, 2019 11:20 AM

Answers

All replies

  • Check the results in this case:

       File.WriteAllBytes( . . ., output.ToArray() );

    Saturday, January 12, 2019 7:38 PM
  • Check the results in this case:

       File.WriteAllBytes( . . ., output.ToArray() );

    That worked. Could you please explain the reason? Why did it work with one encoder and did not work with the other? Will it write some garbage in the end, e.g. if the allocated buffer is longer than the size of the image?
    Saturday, January 12, 2019 8:51 PM
  • According to documentation, it seems that GetBuffer has sense when a predefined array was specified in the constructor of MemoryStream. Otherwise, maybe it is difficult to determine where the data begin and end.

    In addition, Position reflects the work of the encoder, which probably needs to seek (back) the stream pointer during its work. (To write the file header, for example). It does not necessary correspond to the written amount. You can try using output.Length instead of output.Position, or perform output.Flush() or output.Seek( 0, SeekOrigin.End ) before accessing Position.

    • Edited by Viorel_MVP Saturday, January 12, 2019 9:21 PM
    Saturday, January 12, 2019 9:17 PM