【问题标题】:Resize image as byte array将图像大小调整为字节数组
【发布时间】:2013-10-30 18:44:14
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    来自 MSDN 上的 PixelDataProvider class

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

    这意味着您只需要在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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2021-09-06
      • 2013-10-24
      • 2019-04-18
      相关资源
      最近更新 更多