Udostępnij za pośrednictwem


Working with Streams: Creating RandomAccessStreamReference from Image downloaded from Web.

I am currently writing my first windows 8 applications. One of the user scenario’s was, to be download images from a website and to be able to share it with other apps using share contract. I had to spend quite a bit of time to figure out how to do this. I decided to put together a blog post with various samples on how to work with streams.

Scenario 1: Download image as Bytes and convert into RandomAccessStreamReference.

In order to share image data, we need object of type “RandomAccessStreamReference”.

  • Download the image data using HttpClient class.
  • Write this data into IRandomAccessStream. There are a few WinRT classes which implement the IRandomAccessStream interface. I will use InMemoryRandomAccessStream, as I do not need to store the data in a file, an in memory stream should suffice. In order to write to the InMemoryRandomAccessStream, we need to acquire it as a writable stream (IOutputStream) and then write to it using a DataWriter class.
  • Create the RandomAccessStreamReference, to be used to set the bitmap data for the share data package

 

Scenario 2: Download image from a website as a stream and create a RandomAccessStreamReference from it  

  • Download the image as Stream. This returns a non seekable stream (this means we cannot read the size or length of the stream, during read operations. 

 

  • Convert the Non Seekable stream into an IRandomAccessStream. I have created an extension method to do this .

 

  • Use the IRandomAccessStream and created the RandomAccessStreamReference to set the bitmap data.

 

Comments

  • Anonymous
    August 15, 2013
    Thanks for the post! One suggestion: it would be great if the code were available as text instead of an image to make it easy to copy and paste.