2015-12-18 32 views
4

我試圖在UWP上使用C#將文件系統的BitmapImage存儲到文件系統中。該圖像使用圖形api從Facebook下載並作爲BitmapImage返回。這部分的工作,並獲取圖像(一旦我可以儲存它,只下降了本地文件夾的圖片測試)我使用下面的代碼:在LocalFolder中存儲BitmapImage - UWP

public static async Task<BitmapImage> GetProfilePicture(string userId){ 
    BitmapImage profilePicture = new BitmapImage(); 

    StorageFolder pictureFolder = await 
        ApplicationData.Current.LocalFolder.GetFolderAsync("ProfilePictures"); 
    StorageFile pictureFile = await pictureFolder.GetFileAsync(userId + ".jpg"); 
    IRandomAccessStream stream = await pictureFile.OpenAsync(FileAccessMode.Read); 
    profilePicture.SetSource(stream); 

    return profilePicture; 

這工作一樣,所以什麼我想只是做相反的事情。優選的結果是這樣的:

public static async void SaveBitmapToFile(BitmapImage image, userId){ 
    StorageFolder pictureFolder = await 
     ApplicationData.Current.LocalFolder.CreateFolderAsync(
      "ProfilePictures",CreationCollisionOption.OpenIfExists); 

     //save bitmap to pictureFolder with name userId.jpg 

} 

我搜索遠播試圖找到一個解決方案,但我似乎無法找到任何對UWP平臺。如何將保存位圖文件?如果使用其他擴展程序更容易,擴展名不一定是.jpg。

回答

5

如果您使用了WriteableBitmap,會更容易。例如,第一種方法將被:

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

然後,你可以這樣做:

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(); 
    } 
} 
+2

這不是一個正確的答案,我需要的是,位圖圖像轉換爲存儲文件 –

+2

下投票,因爲問題具體是關於保存BitmapImage。 – Daredevil