Click here to Skip to main content
15,887,854 members
Articles / Desktop Programming / WPF
Tip/Trick

Conversion between File, Byte , Stream,BitmapImage and WriteableBitmap

Rate me:
Please Sign up or sign in to vote.
4.40/5 (4 votes)
5 Aug 2014CPOL 20.5K   6  
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[]

C++
            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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Microsoft Student Partners
Tunisia Tunisia
I study Software Engineering , 23 years old , I'm motivated with all Technologies of Microsoft.
Since I have been in the Community of Microsoft as Microsoft Student Partners, I developped many apps on the platform Windows and Phone. Now , it's time to share what I learn here and I'am ready to help Everyone.
You can contact me at any time (anisderbel@outlook.com)
This is a Organisation

9 members

Comments and Discussions

 
-- There are no messages in this forum --