Create an Image or Bitmap Image from a Byte[], and a Byte[] from an image.
Have a filestream set up and need to produce an Image or Bitmap image from the blob? No worries, there are a few ways in doing this. First off, let me show you how to create the image or bitmap image from the byte array.
To an image specifically.
public Image byteArrayToImage(byte[] Inbyte) { MemoryStream mStream = new MemoryStream(Inbyte); Image _image = Image.FromStream(mStream ); return _image ; }
To a bitmap specifically.
public BitmapImage byteArrayToBitmap(byte[] Inbyte) { MemoryStream mStream = new MemoryStream(Inbyte); BitmapImage _bitmap = new BitmapImage(); _bitmap .BeginInit(); _bitmap .StreamSource = mStream ; _bitmap .EndInit(); return _bitmap ; }
Both.
public void WriteImageToFile(byte[] Inbyte, String FileName) { FileStream aFile = new FileStream(FileName, FileMode.Create); //Write from the Inbyte byte array to the file aFile.Seek(0, SeekOrigin.Begin); aFile.Write(Inbyte, 0, Inbyte.Length); aFile.Close(); }
Now you are wondering how to get the image in the byte[] in the first place. Well that part is very simple. Here is a function that will read in the image and return the byte array for you
public void ImageTobyteArray(string Filepath) { System.IO.File.ReadAllBytes(Filepath); }