0

The simplest way to decode a PNG from a stream is:

Bitmap png = new Bitmap(Image.FromStream(pngStream));

But this don't allow us to decode the PNG to an existing buffer. So if we use this way, Image.FromStream(..) has to allocate new memory for the image data every time we call it (and then GC has to collect the used memory every time too).

There is also PngBitmapDecoder, but it takes a Stream reference in constructors and decode the PNG inside constructors and has no other functions to do it, so i have to create new PngBitmapDecoder every time too.

So i want some ways to pass a reference/pointer to an existing byte buffer, so a PNG decoder use it every time, no redundant allocations/deallocations.

Is there other standard ways to do it or you can advise some 3rd-party libraries for .Net 4.6.2 to do this?

Emil Kabirov
  • 559
  • 4
  • 14
  • 1
    It's unclear what your goal is and why you think allocating a `Bitmap` or `PngBitmapDecoder` is “redundant”. 3rd-party suggestions are off-topic; but you may want to consider [SharpDX](https://stackoverflow.com/questions/9151615/); which provides both a streaming and buffer-based API to the [Windows Imaging Component](https://msdn.microsoft.com/en-us/library/windows/desktop/ee719654(v=vs.85).aspx), and is higher performance than GDI+. – Dour High Arch Mar 04 '18 at 23:16
  • I have a high-loaded HTTP web-service processing images. Every time it receives an encoded PNG from a request and decodes it. The number of requests per a second is big. So i would not spend CPU time for memory allocations and deallocations if i can avoid this using preallocated buffer. Thank you! – Emil Kabirov Mar 04 '18 at 23:23
  • I want to allocate a byte array and pin it with GCHandle, so GC won't move the array to another place in memory. – Emil Kabirov Mar 04 '18 at 23:27
  • `Bitmap` is almost completely unmanaged component, it does not allocate managed byte arrays. Side note: you can pass `Stream` directly into `Bitmap` constructor. – Evk Mar 05 '18 at 04:57

0 Answers0