gpt4 book ai didi

windows-8 - 将图像调整为字节数组

转载 作者:行者123 更新时间:2023-12-03 08:05:26 25 4
gpt4 key购买 nike

我正在开发 Windows 8 应用程序。我想将调整大小的图像作为字节。所以我的方法将获取 StorageFile、高度和宽度,它会返回 byte[] 或调整大小的图像。下面给出了我到目前为止所做的尝试。我的努力返回了所有值为 0 的 byte[]。

PS:我不想创建新的调整大小的 StorageFile,也不想只将 WritableBitmapEx 用于一种方法。

private async Task<byte[]> ResizeImage(StorageFile BigFile, uint finalHeight, uint finalWidth)
{
using (var sourceStream = await BigFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
BitmapTransform transform = new BitmapTransform() { ScaledHeight = finalHeight, ScaledWidth = finalWidth };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);

InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();

BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, finalWidth, finalHeight, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();

var bb = new byte[ras.Size];
await ras.ReadAsync(bb.AsBuffer(), (uint)ras.Size, InputStreamOptions.None);
return bb;
}
}

最佳答案

来自PixelDataProvider class在 MSDN:

An application asynchronously receives a PixelDataProvider from the GetPixelDataAsync methods of BitmapFrame or BitmapDecoder. The application can then synchronously request the pixel data using DetachPixelData to get access to the raw pixels of the bitmap.

这意味着您只需在 PixelDataProvider 对象上调用 DetachPixelData:

private async Task<byte[]> ResizeImage(StorageFile BigFile, uint finalHeight, uint finalWidth)
{
using (var sourceStream = await BigFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
BitmapTransform transform = new BitmapTransform() { ScaledHeight = finalHeight, ScaledWidth = finalWidth };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);

byte[] buffer = pixelData.DetachPixelData();
return buffer;
}
}

关于windows-8 - 将图像调整为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19691292/

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