gpt4 book ai didi

c# - BitmapSource.CopyPixels->byte[]->BitmapSource 怎么做这个简单?

转载 作者:行者123 更新时间:2023-11-30 13:40:17 25 4
gpt4 key购买 nike

如何在 C# 中高效地将 BitmapSource 转换为 byte[],反之亦然?

最佳答案

BitmapSource 到 byte[]:

private byte[] BitmapSourceToArray(BitmapSource bitmapSource)
{
// Stride = (width) x (bytes per pixel)
int stride = (int)bitmapSource.PixelWidth * (bitmapSource.Format.BitsPerPixel / 8);
byte[] pixels = new byte[(int)bitmapSource.PixelHeight * stride];

bitmapSource.CopyPixels(pixels, stride, 0);

return pixels;
}

byte[] 到 BitmapSource:

private BitmapSource BitmapSourceFromArray(byte[] pixels, int width, int height)
{
WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * (bitmap.Format.BitsPerPixel / 8), 0);

return bitmap;
}

关于c# - BitmapSource.CopyPixels->byte[]->BitmapSource 怎么做这个简单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8311805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com