How to share filtered image in UWP C#

别等时光非礼了梦想. 提交于 2019-12-24 00:59:37

问题


I have an image processing windows 10 application. I am applying filters on that image and showing it on the image element. This is how I am applyting filter and setting it as a source to MainImage element.

 ProcessImage processImage = new ProcessImage(sourcePixels, width, height);

       byte[] blurEffect = processImage.BlurEffect(width, height);

        WriteableBitmap blurImage = new WriteableBitmap((int)width, (int)height);
        using (Stream stream = blurImage.PixelBuffer.AsStream())
        {
            await stream.WriteAsync(blurEffect, 0, blurEffect.Length);
            MainImage.Source = blurImage;
        }

Up till now I have set the WriteableBitmap image to the source. Now I want to share this image using DataTransferManager's Data requested event as shown

 dataTransferManager = DataTransferManager.GetForCurrentView();
        dataTransferManager.DataRequested += DataTransferManager_DataRequested;

The body of its event containing this code

 DataPackage dataPackage = args.Request.Data;
        dataPackage.Properties.Title = "App Name";
        dataPackage.Properties.Description = "My description";

        dataPackage.SetBitmap();

On the share button click event, i am calling showshareUI like this

DataTransferManager.ShowShareUI();

I am trying to share image using fourth line above that is SetBitmap method, but the problem here is this method want RandomAccessStreamReference value and I have a filtered image of type writeablebitmap. How can I get this thing done?


回答1:


You can write your WriteableBitmap to an InMemoryRandomAccessStream

I don't have access to my dev machine so I can't test it but here's a quick sample:

private async Task<IRandomAccessStream> Convert(WriteableBitmap writeableBitmap)
    {
        var stream = new InMemoryRandomAccessStream();

        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        Stream pixelStream = writeableBitmap.PixelBuffer.AsStream();
        byte[] pixels = new byte[pixelStream.Length];
        await pixelStream.ReadAsync(pixels, 0, pixels.Length);

        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96.0, 96.0, pixels);
        await encoder.FlushAsync();

        return stream;
    }

Since dataPackage.SetBitmap() expects a RandomAccessStreamReference object you will need to obtain one based on the IRandomAccessStream that the above method returns. Fortunately that is pretty easy:

var streamRef = RandomAccessStreamReference.CreateFromStream(stream)

Hope that works.



来源:https://stackoverflow.com/questions/37732360/how-to-share-filtered-image-in-uwp-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!