65.9K
CodeProject is changing. Read more.
Home

Conversion between File, Byte , Stream,BitmapImage and WriteableBitmap

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.40/5 (4 votes)

Aug 5, 2014

CPOL
viewsIcon

21107

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 ;)