Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Conversion between File, Byte , Stream,BitmapImage and WriteableBitmap

0.00/5 (No votes)
5 Aug 2014 3  
This tip resume the majority types of conversion that we need while developing

Introduction

While developing , we need sometimes to convert the Image in many types then we can modify them as we want or to store them in a Database...

Using the code

1-Convert File to Byte[]

            byte[] fileBytes = null;
            if (file != null)
            {
                using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
                {
                    fileBytes = new byte[stream.Size];
                    using (DataReader reader = new DataReader(stream))
                    {
                        await reader.LoadAsync((uint)stream.Size);
                        reader.ReadBytes(fileBytes);
                    }
                }
            }

2-Convert Byte[] to BitmapImage

using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                {
                   
                    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes((byte[])fileBytes);
                        writer.StoreAsync().GetResults();
                    }
                   

                    var image = new BitmapImage();
                    image.SetSource(ms);
               }

3-Convert Byte[] to Stream

  Stream stream = new MemoryStream(fileBytes);

4-Convert  Stream to WriteableBitmap

  WriteableBitmap writimage = new WriteableBitmap(1, 1);
  BitmapPixelFormat format = BitmapPixelFormat.Unknown;

  writimage = await WriteableBitmapExtensions.FromStream(writimage, stream, format);
  writimage.SetSource(ms);

5-Convert  File to BitmapImage

BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));

History

these conversions can facilitate your work , you will find what you need with only one page ;)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here