Universal App圖片文件和圖片byte[]信息轉換為bitmap


1. 打開圖片文件並轉換為BitmapImage類

 首先要做的自然是打開一個圖片文件了,可以使用FileOpenPicker來手動選擇圖片,總之能拿到一個StorageFile都行。

//打開圖片選擇器,選擇要發送的圖片
var openPicker = new FileOpenPicker
{
  ViewMode = PickerViewMode.Thumbnail,
   SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
var file = await openPicker.PickSingleFileAsync();

也可以使用StorageFile.GetFileFromApplicationUriAsync獲取,下面代碼得到的文件是應用獨立存儲文件夾LocalState里的1.jpg文件。

var path = "ms-appdata:///local/1.jpg";
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));

接下來將文件打開,並把文件流寫入到BitmapImage中。

//將圖片文件讀取為BitmapImage
var fileStream = await file.OpenReadAsync();
var bitmap = new BitmapImage();
await bitmap.SetSourceAsync(fileStream);

 

2. 將圖片byte[]信息轉換為bitmap

首先要把byte[]轉換為IRandomAccessStream然后再使用BitmapImage.SetSourceAsync方法將流寫入bitmap中,單純的MemoryStream是不能直接寫入到bitmap中的。

public async static Task<BitmapImage> ConvertBytesToBitmapImage(byte[] bytes)
{
        try
            {
                if (bytes == null || bytes.Length == 0) return null;

                var stream = new MemoryStream(bytes);
                var randomAccessStream = new InMemoryRandomAccessStream();
                using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
                {
                    var dw = new DataWriter(outputStream);
                    var task = new Task(() => dw.WriteBytes(stream.ToArray()));
                    task.Start();
                    await task;
                    await dw.StoreAsync();
                    await outputStream.FlushAsync();

                    var bitmapImage = new BitmapImage();
                    await bitmapImage.SetSourceAsync(iRandomAccessStream);
                    return bitmapImage;
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine("[Error] Convert bytes to BitmapImage failed,exception:{0}", exception);
                return null;
            }
}                

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM