Storing a BitmapImage in LocalFolder - UWP

独自空忆成欢 提交于 2019-12-04 10:24:11
Igor Ralic

It would be easier if you used a WriteableBitmap. For example, the first method would then be:

public static async Task<WriteableBitmap> GetProfilePictureAsync(string userId)
{
    StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("ProfilePictures");
    StorageFile pictureFile = await pictureFolder.GetFileAsync(userId + ".jpg");

    using (IRandomAccessStream stream = await pictureFile .OpenAsync(FileAccessMode.Read))
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
        WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);

        await bmp.SetSourceAsync(stream);

        return bmp;
    }
}

Then you could do:

public static async Task SaveBitmapToFileAsync(WriteableBitmap image, userId)
{
    StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePictures",CreationCollisionOption.OpenIfExists);
    var file = await pictureFolder.CreateFileAsync(userId + ".jpg", CreationCollisionOption.ReplaceExisting);

    using (var stream = await file.OpenStreamForWriteAsync())
    {
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream());
        var pixelStream = image.PixelBuffer.AsStream();
        byte[] pixels = new byte[bmp.PixelBuffer.Length];

        await pixelStream.ReadAsync(pixels, 0, pixels.Length);

        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels);

        await encoder.FlushAsync();
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!