48

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.??

3
  • 3
    which line throws that exception? Commented Mar 5, 2012 at 9:33
  • System.Drawing.Image img = System.Drawing.Image.FromStream(stream); this code throws the mentioned exception... Commented Mar 5, 2012 at 9:53
  • @BijoyKJose I know this is a long time ago, but have you found a solution to the issue "No imaging component suitable to complete this operation was found". I'm having the same issue at the moment and I can't find any solution. Commented Aug 18, 2016 at 12:05

4 Answers 4

99

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;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I modified my own code snippet and i used yours as well.. but both throws exception "No imaging component suitable to complete this operation was found" after executing image.EndInit(); any solution for this..?
is your imageData set? This method works if the bytes are saved first to a stream or if you load a image-file's bytes into memory - see here: msdn.microsoft.com/de-de/library/…
@RandomDev Hi, what do you mean by saving ? I dont have good grasp on it, I am loading the bytes from my database
20

If you have array like this:

byte[] byteArrayIn = new byte[] {255, 128, 0, 200};

And you want something like: enter image description here

Use:

BitmapSource bitmapSource = BitmapSource.Create(2, 2, 300, 300,PixelFormats.Indexed8,    BitmapPalettes.Gray256, byteArrayIn, 2);

Image.Source = bitmapSource;

In xaml:

<Image RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" x:Name="Image"></Image>   

1 Comment

Your answer saved my day! Easy to understand just the essence. After 2 hours messing around with Pixelformats and BitmapPalettes it's funny to see how easy it really is.
6
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnBrowse_Click(object sender, RoutedEventArgs e)
    {
        var of = new OpenFileDialog();
        of.Filter = "Image files (*.png;*.jpeg)|*.png;*.jpeg|All files (*.*)|*.*";
        var res = of.ShowDialog();
        if (res.HasValue)
        {
            imgPreview.Source = new BitmapImage(new Uri(of.FileName));

            var t = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source as BitmapSource);
            var d = Utils.ConvertBitmapSourceToByteArray(new BitmapImage(new Uri(of.FileName)));
            var s = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source);
            var enc = Utils.ConvertBitmapSourceToByteArray(new PngBitmapEncoder(), imgPreview.Source);
            //imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage(enc);
            imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage2(enc);
            //var i = 0;


        }
        else
        {
            MessageBox.Show("Select a currect file...");

        }
    }

}

/util.cs/

public class Utils
{
    public static byte[] ConvertBitmapSourceToByteArray(BitmapEncoder encoder, ImageSource imageSource)
    {
        byte[] bytes = null;
        var bitmapSource = imageSource as BitmapSource;

        if (bitmapSource != null)
        {
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

            using (var stream = new MemoryStream())
            {
                encoder.Save(stream);
                bytes = stream.ToArray();
            }
        }

        return bytes;
    }

    public static byte[] ConvertBitmapSourceToByteArray(BitmapSource image)
    {
        byte[] data;
        BitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }
    public static byte[] ConvertBitmapSourceToByteArray(ImageSource imageSource)
    {
        var image = imageSource as BitmapSource;
        byte[] data;
        BitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }
    public static byte[] ConvertBitmapSourceToByteArray(Uri uri)
    {
        var image = new BitmapImage(uri);
        byte[] data;
        BitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }
    public static byte[] ConvertBitmapSourceToByteArray(string filepath)
    {
        var image = new BitmapImage(new Uri(filepath));
        byte[] data;
        BitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }

    public static BitmapImage ConvertByteArrayToBitmapImage(Byte[] bytes)
    {
        var stream = new MemoryStream(bytes);
        stream.Seek(0, SeekOrigin.Begin);
        var image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = stream;
        image.EndInit();
        return image;
    }
}

Comments

0

Hope this would help, let's consider you get the Image from the database as varbinary in a dataset among other rows retrieved from the database , either from the stored procedure or direct command line.

Here is the XAML

   <Image x:Name="SelectedImage_IMG"/>

Here is the Code-Behind

    // your code to get data to a DataSet (ds)
    byte[] imageData = (byte[])ds.Tables[0].Rows[0][10]; // (yours might differ)
    SelectedImage_IMG.Source = ConvertToBitmap(imageData);

Here is the method or function to ConvertToBitmap()

   public BitmapImage ConvertToBitmap(byte[] imageData)
        {
            BitmapImage bmp = new BitmapImage();

            using (MemoryStream strm = new MemoryStream())
            using (MemoryStream ms = new MemoryStream())
            {
                strm.Write(imageData, 0 , imageData.Length);
                strm.Position = 0;

                System.Drawing.Image img = System.Drawing.Image.FromStream(strm);

                img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                ms.Seek(0, SeekOrigin.Begin);

                bmp.BeginInit();
                bmp.CacheOption = BitmapCacheOption.OnLoad;
                bmp.StreamSource = ms;
                bmp.EndInit();
                bmp.Freeze();

                return bmp;
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.