我目前正在为Windows应用商店编写一个小型图像编辑应用程序,我想在其中使用编辑图像的共享魅力。由于某些应用程序只接受StorageFiles而不是Bitmaps(如默认的Mail App),我想以两种方式提供图像,如下所述: http://www.jeffblankenburg.com/2012/11/07/31-days-of-windows-8-day-7-share-contract 但是,我不知道如何从WrieableBitmap创建StorageFile。
也许你可以帮我完成下面的代码。
// Share Image
async void dtm_DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
DataRequestDeferral deferral = e.Request.GetDeferral();
DataPackage requestData = e.Request.Data;
requestData.Properties.Title = "My Image";
requestData.Properties.Description = "Created using a Windows Store App.";
// This stream is to create a bitmap image later
IRandomAccessStream stream = new InMemoryRandomAccessStream();
// Determin which type of BitmapEncoder we should create
Guid encoderId = BitmapEncoder.JpegEncoderId;
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
Stream pixelStream = theImage.PixelBuffer.AsStream();
byte[] pixels = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)theImage.PixelWidth, (uint)theImage.PixelHeight, 96.0, 96.0, pixels);
requestData.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
// What goes here?
StorageFile storageFileImage =
List<IStorageItem> files = new List<IStorageItem>();
files.Add(storageFileImage);
requestData.SetStorageItems(files);
requestData.Properties.Thumbnail = RandomAccessStreamReference.CreateFromStream(stream);
await encoder.FlushAsync();
deferral.Complete();
}
答案 0 :(得分:1)
下面显示了如何将WriteableBitmap wb编码为图片库中的StorageFile。
private static async Task<StorageFile> SaveAsJpeg(WriteableBitmap wb)
{
byte[] pixels;
using (var stream = wb.PixelBuffer.AsStream())
{
pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
}
var name = String.Format("{0}_{1:yyyy-MM-dd_HH-mm-ss}.jpg", "MyApp", DateTime.Now);
var outputFile = await KnownFolders.PicturesLibrary.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writeStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
(uint)wb.PixelWidth, (uint)wb.PixelHeight,
96, 96, pixels);
await encoder.FlushAsync();
using (var outputStream = writeStream.GetOutputStreamAt(0))
{
await outputStream.FlushAsync();
}
}
return outputFile;
}