In WinRT, how do I load an image and then wait only as long as is needed for it to load before writing to it?

后端 未结 3 1313
有刺的猬
有刺的猬 2021-01-15 13:51

I\'m using WriteableBitmapEx in a WinRT project. I load an image into a WriteableBitmap from the users Picture library. However, I cannot then immediately write to that im

3条回答
  •  感动是毒
    2021-01-15 14:19

    This method loads an image from the app's content, decodes it and passes back an ready-to-use WriteableBitmap. Taken from the WriteableBitmapEx library:

    /// 
    /// Loads an image from the applications content and fills this WriteableBitmap with it.
    /// 
    /// The WriteableBitmap.
    /// The URI to the content file.
    /// The WriteableBitmap that was passed as parameter.
    public static async Task FromContent(this WriteableBitmap bmp, Uri uri)
    {
       // Decode pixel data
       var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
       var decoder = await BitmapDecoder.CreateAsync(await file.OpenAsync(FileAccessMode.Read));
       var transform = new global::Windows.Graphics.Imaging.BitmapTransform();
       var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
       var pixels = pixelData.DetachPixelData();
    
       // Copy to WriteableBitmap
       bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
       using (var bmpStream = bmp.PixelBuffer.AsStream())
       {
          bmpStream.Seek(0, SeekOrigin.Begin);
          bmpStream.Write(pixels, 0, (int)bmpStream.Length);
          return bmp;
       }
    }
    

    BTW, WinRT is now officially supported by WriteableBitmapEx. ;) http://kodierer.blogspot.de/2012/05/one-bitmap-to-rule-them-all.html

提交回复
热议问题