Search code examples
c#imagepixelformat

Create image from stream with correct pixel format


I created a web service in .Net Core. This service return an image png with pixel format 8pp indexed :

using (Bitmap bmp = new Bitmap(img.width, img.height, PixelFormat.Format8bppIndexed))
{
    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, imgFormat);
        return new FileContentResult(ms.ToArray(), $"image/png");
    }
}

I want to test this service, so I created a C# test with this piece of code :

Task<HttpResponseMessage> responseTask = client.PostAsync(url, content);
responseTask.Wait();
var response = responseTask.Result;

HttpContent ct = response.Content;
byte[] data = await ct.ReadAsByteArrayAsync();
using (MemoryStream m = new MemoryStream(data))
{                         
    Bitmap img = new Bitmap(m);
    img.Save(filePath, ImageFormat.Png);
}

But the Bitmap img is Format32bppArgb. How can I do to get my image in original format (Format8bppIndexed) ?


Solution

  • Just save straighway what you got:

    using (var fs = new FileStream(filePath, FileMode.Create))
        fs.Write(data, 0, data.Length);