convert binary to bitmap using memory stream - c#

Hi I wanna convert binary array to bitmap and show image in a picturebox. I wrote the following code but I got exception that says that the parameter is not valid .
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream);
mStream.Dispose();
return bm;
}

It really depends on what is in blob. Is it a valid bitmap format (like PNG, BMP, GIF, etc?). If it is raw byte information about the pixels in the bitmap, you can not do it like that.
It may help to rewind the stream to the beginning using mStream.Seek(0, SeekOrigin.Begin) before the line Bitmap bm = new Bitmap(mStream);.
public static Bitmap ByteToImage(byte[] blob)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}

Don't dispose of the MemoryStream. It now belongs to the image object and will be disposed when you dispose the image.
Also consider doing it like this
var ms = new MemoryStream(blob);
var img = Image.FromStream(ms);
.....
img.Dispose(); //once you are done with the image.

System.IO.MemoryStream mStrm = new System.IO.MemoryStream(your byte array);
Image im = Image.FromStream(mStrm);
im.Save("image.bmp");
Try this. If you still get any error or exception; please post your bytes which you are trying to convert to image. There should be problem in your image stream....

Related

Value cannot be null. Parameter name: encoder in bitmap casting c#

In order to convert bitmap to base64 i have to convert my bitmap to Image
I get this message when i'm converting an image to memorystream as img.Save(ms, img.RawFormat); after casting my image from a screenshoot bitmap like Image img = (Image)bitmap; or Image img = bitmap as Image, but it's working fine when i use local stored image like Image img = Image.FromFile(Path).
how can i avoid this error while i don't want to store the screenshoot and read it again each time
this is the code i have tried
Image img = bitmap as Image;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
string base64 = Convert.ToBase64String(ms.ToArray());
}
Actually, you don't have to convert Bitmab to Image while you can encode your Bitmab with Base64 directly
try this:
using (MemoryStream ms = new MemoryStream())
{
bitmab.Save(ms, ImageFormat.Jpeg); // you can change your image format as you want
byte[] imageBytes = ms.ToArray();
string base64 = Convert.ToBase64String(imageBytes);
}

JpegBitmapEncoder cannot access closed stream

I have a BitmapSource loaded from a byte array this way:
BitmapSource bitmap = null;
using (var stream = new MemoryStream(bytes))
{
var decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
bitmap = decoder.Frames[0];
stream.Flush();
}
return bitmap;
When I'm trying to write this as an JPEG to disk, it only throws an error:
Any ideas here? Other ways of writing the image to disk?

How to convert Bitmap image to byte array in wp7?

using (MemoryStream ms = new MemoryStream())
{
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri("/Images/chef.png", UriKind.Relative);
WriteableBitmap LoadedPhoto = new WriteableBitmap(image);
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight,0,95);
ms.Seek(0, 0);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
ms.Close();
}
I am getting NullReferenceException at image, but my path is also correct and image also exists.
WriteableBitmap LoadedPhoto = new WriteableBitmap(image);
Is anything goes wrong.
Please Refer the solution.
which shows the solution to converting the bitmapimages to byte array.
I hope you will understand..
conversion of bitmapimage to byte array
Refer this link..

Convert a bitmap into a byte array

Using C#, is there a better way to convert a Windows Bitmap to a byte[] than saving to a temporary file and reading the result using a FileStream?
There are a couple ways.
ImageConverter
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
This one is convenient because it doesn't require a lot of code.
Memory Stream
public static byte[] ImageToByte2(Image img)
{
using (var stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.
Source: http://www.vcskicks.com/image-to-byte.php
A MemoryStream can be helpful for this. You could put it in an extension method:
public static class ImageExtensions
{
public static byte[] ToByteArray(this Image image, ImageFormat format)
{
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
return ms.ToArray();
}
}
}
You could just use it like:
var image = new Bitmap(10, 10);
// Draw your image
byte[] arr = image.ToByteArray(ImageFormat.Bmp);
I partially disagree with prestomanifto's answer in regards to the ImageConverter. Do not use ImageConverter. There's nothing technically wrong with it, but simply the fact that it uses boxing/unboxing from object tells me it's code from the old dark places of the .NET framework and its not ideal to use with image processing (it's overkill for converting to a byte[] at least), especially when you consider the following.
I took a look at the ImageConverter code used by the .Net framework, and internally it uses code almost identical to the one I provided above. It creates a new MemoryStream, saves the Bitmap in whatever format it was in when you provided it, and returns the array. Skip the extra overhead of creating an ImageConverter class by using MemoryStream
You can also just Marshal.Copy the bitmap data. No intermediary memorystream etc. and a fast memory copy. This should work on both 24-bit and 32-bit bitmaps.
public static byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmpdata = null;
try
{
bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int numbytes = bmpdata.Stride * bitmap.Height;
byte[] bytedata = new byte[numbytes];
IntPtr ptr = bmpdata.Scan0;
Marshal.Copy(ptr, bytedata, 0, numbytes);
return bytedata;
}
finally
{
if (bmpdata != null)
bitmap.UnlockBits(bmpdata);
}
}
.
Save the Image to a MemoryStream and then grab the byte array.
http://msdn.microsoft.com/en-us/library/ms142148.aspx
Byte[] data;
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Bmp);
data = memoryStream.ToArray();
}
Use a MemoryStream instead of a FileStream, like this:
MemoryStream ms = new MemoryStream();
bmp.Save (ms, ImageFormat.Jpeg);
byte[] bmpBytes = ms.ToArray();
More simple:
return (byte[])System.ComponentModel.TypeDescriptor.GetConverter(pImagen).ConvertTo(pImagen, typeof(byte[]))
Try the following:
MemoryStream stream = new MemoryStream();
Bitmap bitmap = new Bitmap();
bitmap.Save(stream, ImageFormat.Jpeg);
byte[] byteArray = stream.GetBuffer();
Make sure you are using:
System.Drawing & using System.Drawing.Imaging;
I believe you may simply do:
ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));
MemoryStream ms = new MemoryStream();
yourBitmap.Save(ms, ImageFormat.Bmp);
byte[] bitmapData = ms.ToArray();
Very simple use this just in one line:
byte[] imgdata = File.ReadAllBytes(#"C:\download.png");

How to Convert system.windows.controls.image to byte[]

I need to convert System.Windows.Controls.Image to byte[].
How to do it ?
Assuming that you answer my query above that you are actually trying to convert an image into a byte array rather than an image control into a byte array here is the code to do so;
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
In general, to convert an object to a byte array, you may want to use binary serialization. This will generate a memory stream from which you can extract a byte array.
You may start with this Question and Answer
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
var uri = new Uri("pack://application:,,,/Images/myImage.jpg");
img.Source = new BitmapImage(uri);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
var bmp = img.Source as BitmapImage;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(ms);
arr = ms.ToArray();
}

Categories