[英]How save BitmapImage WinRT
我有BitmapImage:
BitmapImage image = new BitmapImage();
image.SetSource(memStream);
我想將圖像保存到磁盤以便將來查看。 我找不到一個如何做到這一點的工作示例? 第二個問題。 我需要獲得一個像素的顏色(如: Color cl=image.GetColorPixel(X,Y)
),我該怎么做? 謝謝!
這是我之前在網絡上發現的代碼。 我不確定,但如果我正確的話,它來自sdk示例或winrt博客
這一切都歸結為WritabelBitmap圖像(就像已發布的其他圖像一樣),創建一個解碼器並將其推送到流中。
/// <summary>
///
/// </summary>
/// <param name="writeableBitmap"></param>
/// <param name="outputFile"></param>
/// <param name="encoderId"></param>
/// <returns></returns>
public static async Task SaveToFile(
this WriteableBitmap writeableBitmap,
IStorageFile outputFile,
Guid encoderId)
{
try
{
Stream stream = writeableBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)writeableBitmap.PixelWidth,
(uint)writeableBitmap.PixelHeight,
96,
96,
pixels);
await encoder.FlushAsync();
using (var outputStream = writeStream.GetOutputStreamAt(0))
{
await outputStream.FlushAsync();
}
}
}
catch (Exception ex)
{
string s = ex.ToString();
}
}
您可以通過以下方式保存BitmapImage。
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await localFolder.CreateFileAsync("image.png");
await FileIO.WriteBytesAsync(sampleFile, bytes);
image.png將保存在Application的LocalFolder中。
希望能幫助到你!
您無法保存或修改BitmapImage
。 您需要使用WriteableBitmap
。 如果您真的別無選擇,只能從BitmapImage開始 - 請檢查其UriSource
屬性,以便再次下載相同的圖像,或者加載與起始BitmapImage
具有相同內容的WriteableBitmap
。 請注意,在某些情況下, UriSource
可能為null - 即使通過為其提供URI來加載BitmapImage
- 也可以手動重置或通過將CacheMode
設置為使用給定BitmapImage
作為其Source
的Image
上的BitmapCache
來重置。
看看這個鏈接。 有一個片段顯示了WriteableBitmap的一些操作http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx
這個例子是閱讀,但寫作應該不難。
要遍歷像素,請查看PixelData屬性。
如果你試圖從你的xaml中取一個ui元素並將其保存為圖像,那就不幸了。 在wpf中,有一個可寫位圖的方法,它將UIelement作為參數但在Windows應用商店中不存在。
您可以使用DirectX,但這是一種非常復雜的方法。 商店中的大多數繪圖應用程序都使用JavaScript,因為它更容易進行保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.