将图像大小调整为字节数组

时间:2013-10-30 18:44:15

标签: windows-8 windows-runtime microsoft-metro windows-store-apps byte

我正在开发Windows 8应用程序。我希望将调整大小的图像作为字节。所以我的方法将获得StorageFile,height&宽度,它将返回byte[]或调整大小的图像。我到目前为止所做的尝试如下。我的努力返回byte [],所有值都为0。

PS:我不想创建新的Resized 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;
    }
}

1 个答案:

答案 0 :(得分:3)

来自MSDN上的PixelDataProvider class

  

应用程序从BitmapFrame或BitmapDecoder的GetPixelDataAsync方法异步接收PixelDataProvider。然后,应用程序可以使用DetachPixelData同步请求像素数据,以访问位图的原始像素。

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

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