在Windows 8.1中共享图像

时间:2014-07-20 00:36:06

标签: c# windows-8.1

我想在我的应用中分享图片。我只是在我的xaml中有一个图像,其源是在运行时通过将canvas作为位图来设置的。我想要共享其源在运行时设置的图像。

这是我的c#代码

 private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(canvas);
        myImg.Source = renderTargetBitmap;
    }

This示例分享已安装位置的图片,如何修改该图片以分享我的图片?

1 个答案:

答案 0 :(得分:2)

您需要将位图转换为RandomAccessStream,然后使用SetBitmap方法使用该流:

args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));

完整代码:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    DataTransferManager.GetForCurrentView().DataRequested+= MainPage_DataRequested;
}

private async void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
    var deferral = args.Request.GetDeferral();
    var bitmap = new RenderTargetBitmap();
    await bitmap.RenderAsync(canvas);

    // 1. Get the pixels
    IBuffer pixelBuffer = await bitmap.GetPixelsAsync();
    byte[] pixels = pixelBuffer.ToArray();

    // 2. Write the pixels to a InMemoryRandomAccessStream
    var stream = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96,
        pixels);

    await encoder.FlushAsync();
    stream.Seek(0);

    // 3. Share it
    args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
    args.Request.Data.Properties.Description = "description";
    args.Request.Data.Properties.Title = "title";
    deferral.Complete();
}

消息来源:http://social.technet.microsoft.com/wiki/contents/articles/20648.using-the-rendertargetbitmap-in-windows-store-apps-with-xaml-and-c.aspx