1

我想分享一个可写位图,但是当我打开分享目标应用程序时,没有图像。下面是我的代码。

private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
    {
        DataPackage requestData = e.Request.Data;
        requestData.Properties.Title = "Image";

        Guid encoderId;
        switch (file.FileType)
        {
            case ".png":
                encoderId = BitmapEncoder.PngEncoderId;
                break;
            case ".jpg":
            case ".jpeg":
            default:
                encoderId = BitmapEncoder.JpegEncoderId;
                break;
        }

        DataRequestDeferral deferral = e.Request.GetDeferral();
        try
        {
            using (IRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
                // image is the WriteableBitmap
                Stream pixelStream = image.PixelBuffer.AsStream();
                byte[] pixels = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96.0, 96.0, pixels);
                await encoder.FlushAsync();
                RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromStream(stream);
                requestData.Properties.Thumbnail = rasr;
                requestData.SetBitmap(rasr);                    
            }
        }
        catch (Exception ex)
        {
            NotifyUser(ex.ToString());
        }
        finally
        {
            deferral.Complete();
        }
    }
4

1 回答 1

2

请试试这个:

private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
        DataRequestDeferral deferral = e.Request.GetDeferral();

        DataPackage requestData = e.Request.Data;
        requestData.Properties.Title = "Image";
        IRandomAccessStream stream = new InMemoryRandomAccessStream();
        Guid encoderId;
        switch (file.FileType)
        {
            case ".png":
                encoderId = BitmapEncoder.PngEncoderId;
                break;
            case ".jpg":
            case ".jpeg":
            default:
                encoderId = BitmapEncoder.JpegEncoderId;
                break;
        }
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
        Stream pixelStream = image.PixelBuffer.AsStream();
        byte[] pixels = new byte[pixelStream.Length];
        await pixelStream.ReadAsync(pixels, 0, pixels.Length);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96.0, 96.0, pixels);
        requestData.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
        await encoder.FlushAsync();

        deferral.Complete();
    }
于 2013-01-16T15:52:20.223 回答