windows-8microsoft-metrowinjs

How to display Windows.Graphics.Imaging.BitmapDecoder in WinJS?


I am trying to make an app that applies filter effects on images. From FilePicker I can get a IRandomAccessStream and I can convert it to BitmapDecoder. But I am not sure how to diplay the bitmap data as image? I do not want to use the file name or path, just want to display the BitmapData as an image. What control should I use in WinJS and how to do it?


Solution

  • These MSDN blogs explain the following process in more detail:

    How to edit an image (XAML)

    How to encode a new image (XAML)

    I found a way to create a BitmapEncoder from a BitmapDecoder. That encoder can be used to create a in memory stream that can be displayed in a field.

           internal async Task<InMemoryRandomAccessStream> applyFilterInternal()
        {
            inputStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
            decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(inputStream);
    
            var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);
    
            encoder.BitmapTransform.ScaledWidth = 640;
            encoder.BitmapTransform.ScaledHeight = 480;
            encoder.BitmapTransform.Rotation = Windows.Graphics.Imaging.BitmapRotation.Clockwise90Degrees;
    
            // Fant is a relatively high quality interpolation algorithm.
            encoder.BitmapTransform.InterpolationMode = Windows.Graphics.Imaging.BitmapInterpolationMode.Fant;
    
            // Attempt to generate a new thumbnail from the updated pixel data.
            // Note: Only JPEG, TIFF and JPEG-XR images support encoding thumbnails.
            encoder.IsThumbnailGenerated = true;
    
            await encoder.FlushAsync();
            return memStream;
        }
    
    public IAsyncOperation<InMemoryRandomAccessStream> applyFilter()
        {
            Task<InMemoryRandomAccessStream> from = applyFilterInternal();
            IAsyncOperation<InMemoryRandomAccessStream> to = from.AsAsyncOperation();
            return to;
        }
    

    To display this -

                filter.applyFilter().then(function (memStream) {
                var msStream = MSApp.createStreamFromInputStream("image/jpeg", memStream);
                var imageURL = URL.createObjectURL(msStream);
                id("imageInput").src = imageURL;
    
            });