Convert byte array to image in wpf

c#, wpf

Solution

Hi this should be working:

    private static BitmapImage LoadImage(byte[] imageData)
    {
        if (imageData == null || imageData.Length == 0) return null;
        var image = new BitmapImage();
        using (var mem = new MemoryStream(imageData))
        {
            mem.Position = 0;
            image.BeginInit();
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.StreamSource = mem;
            image.EndInit();
        }
        image.Freeze();
        return image;
    }

Problem

I used ``` private BitmapImage byteArrayToImage(byte[] byteArrayIn) { try { MemoryStream stream = new MemoryStream(); stream.Write(byteArrayIn, 0, byteArrayIn.Length); stream.Position = 0; System.Drawing.Image img = System.Drawing.Image.FromStream(stream); BitmapImage returnImage = new BitmapImage(); returnImage.BeginInit(); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); returnImage.StreamSource = ms; returnImage.EndInit(); return returnImage; } catch (Exception ex) { throw ex; } return null; } ``` This method in my application to convert byte array to an image. But it throws "Parameter is not valid" exception.. why it is happening..? Is there any alternative method.??

Original source

Related problems