从流以正确的像素格式创建图像

时间:2019-02-06 16:07:45

标签: c# image pixelformat

我在.Net Core中创建了一个Web服务。该服务返回像素格式为8pp的图像png:

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

我想测试此服务,所以我用这段代码创建了一个C#测试:

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

但是位图img是Format32bppArgb。如何获得原始格式(Format8bppIndexed)的图像?

1 个答案:

答案 0 :(得分:1)

直接保存您得到的东西:

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