Na Me
Na Me

Reputation: 389

How to convert a byte-array to a Image in C#?

I've got a SQL Server database in which I store PNG's. The value of the screenshot is in Hex (0x085A3B...). How can I convert from "Screenshot" (my own data type) to "Image" or something similar like "BitmapImage"?

For the beginning, I fetch a screenshot like this:

private Screenshot LoadScreenshot()
{
    using (var context = new Context())
    {
        return context.Screenshots.FirstOrDefault();
    }
}

the method above returns me a byte-array like

byte[40864]

I cant do the following because I get an Exception (I dont know which one and why):

public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit(); //the compiler breaks here
    return image;
}

I'm using C# and WPF

Thank you

EDIT:

Here's my exception:

System.Runtime.Serialization.SafeSerializationManager No imaging component suitable to complete this operation was found

HOW TO SOLVE:

I needed to add this line of code:

Byte[] screenshotBytes = screenshot.Screenshot; //.Screenshot is a byte [] (I dont knwo why it didnt work before)

And @frebinfrancis method

Upvotes: 3

Views: 1560

Answers (2)

Frebin Francis
Frebin Francis

Reputation: 1915

your code is looking good and there is no issues with your code, when i was doing the same thing some images are working for me but some won't.after a long time searching i found this following link.

http://support.microsoft.com/kb/2771290

this is my code:

public BitmapImage ImageFromBuffer(Byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0) return null;
            var image = new BitmapImage();
            using (var mem = new MemoryStream(bytes))
            {
                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;
        }

Upvotes: 3

chouaib
chouaib

Reputation: 2817

Try this one:

public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
  var data = new byte[width * height * 4];

  int o = 0;

  for (var i = 0; i < width * height; i++)
  {
     var value = imageData[i];

     data[o++] = value;
     data[o++] = value;
     data[o++] = value;
     data[o++] = 0;
  }

  unsafe
  {
     fixed (byte* ptr = data)
     {
        using (Bitmap image = new Bitmap(width, height, width * 4,PixelFormat.Format32bppRgb, new IntPtr(ptr)))
        {
           image.Save(Path.ChangeExtension(fileName, ".bmp"));
        }
      }
   }
}

Upvotes: 0

Related Questions