I need to create an Image from a Byte Array but I don't know how to do this. I tried to do it like this:
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
But there was always the message that the parameter ms is not valid.
The exact Exception message is:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
With this I am reading the Array from the database
byte[] bytes = ObjectToByteArray(reader["profilepicture"]);
private byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Can anybody please help me with this problem?
Try this:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Source
Related
Please pardon my knowledge on C# as I am very new to it,I am unable to insert a record in SQL and getting the below error while insert image to SQL.
Error :
Object reference not set to an instance of an object.
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
If i select a image and insert it inserts successfully, but if i do not select an image it throws the above error.
Please help!!
Change this:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
To this
MemoryStream ms = new MemoryStream();
pictureBox1?.Image?.Save(ms, pictureBox1?.Image?.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("#img", (object)img ?? DBNull.Value);
Try testing that PictureBox1.Image exists before referencing it, like this:
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("#img", img);
}
else
{
com.Parameters.Add("#img", SqlDbType.VarBinary, 0).Value = DbNull.Value;
}
EDITED to include comment by GarethD
first, you need to make a new condition to check is file selected or not.here are code below:
if pictureBox1.hasfile == true
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("#img", null);
}
else
{
com.Parameters.AddWithValue("#img", img);
}
}
because you are not selecting any file thats why it throwing exception on runtime
I need to convert a BitmapImage in a byte[] but I don't find how to do it in C# web.
I found examples but none of them work (JpegBitmapEncoder doesn't exist, BitmapImageObject.StreamSource doesn't exist, there isn't WriteableBitmap constructor with BitmapImage as parameter, Extensions.SaveJpeg(parameters) doesn't exist ...).
Examples I found:
Constructor new WriteableBitmap(bitmapImage) doesn't exist.
public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
byte[] data;
// Get an Image Stream
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
// reset the stream pointer to the beginning
ms.Seek(0, 0);
//read the stream into a byte array
data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
}
//data now holds the bytes of the image
return data;
}
new WriteableBitmap(img), System.Windows.Media.Imaging.Extensions.SaveJpeg don't exist.
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
imageSource.StreamSource doesn't exist.
public static byte[] ImageToByte(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
JpegBitmapEncoder doesn't exist.
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
Try with the using statement to a namespace in the beginning of your code.
Otherwise there should be some Nuget packages which you could install to achieve your goal.
using System.Drawing;
In Main method
Image img = Image.FromFile("path to the file");
var byteArray = ImageToByte(img);
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
Try this
I think this will help...
public byte[] ConvertBitMapToByteArray(Bitmap bitmap)
{
byte[] result = null;
if (bitmap != null)
{
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, bitmap.RawFormat);
result = stream.ToArray();
}
return result;
}
byte[] foo = System.IO.File.ReadAllBytes("bitmap path");
Or
byte[] foo;
Object obj = YourBitmap;
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
foo = ms.ToArray();
}
Or
ImageConverter foocon = new ImageConverter();
byte[] foo = (byte[])foocon.ConvertTo(YourBitmap, typeof(byte[]));
Or
MemoryStream ms = new MemoryStream();
Bitmap.Save(ms, YourBitmap.RawFormat);
byte[] foo = ms.ToArray();
Finally, it seems that, obviously, it missed some libraries but we are limited with our application, so we decided to recover our pictures by another way. Anyway, thank you all.
How Do I convert BitmapSource to MemoryStream. Though I tried some code:
private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
Stream bmp;
using (bmp = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(writeBmp));
enc.Save(bmp);
}
return bmp;
}
It doesn't give any error but after putting debugging point it is showing some exceptions which are listed below.
Capacity: 'printStream.Capacity' threw an exception of type
'System.ObjectDisposedException' Length: 'printStream.Length' threw
an exception of type 'System.ObjectDisposedException' Position:
'printStream.Position' threw an exception of type
'System.ObjectDisposedException'
using (bmp = new MemoryStream()) causes bmp object is destroyed on end using block. And You return bmp variable which is destroyed.
Remove using:
private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
Stream bmp = new MemoryStream();
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(writeBmp));
enc.Save(bmp);
return bmp;
}
The problem here is that you are creating bmp inside an using, that's why it has been disposed before you return it (it is disposed once you leave the using) and that explains the exceptions you receive.
private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
Stream bmp= new MemoryStream();
using (enc = new BmpBitmapEncoder())
{
enc.Frames.Add(BitmapFrame.Create(writeBmp));
enc.Save(bmp);
}
return bmp;
}
public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
System.Drawing.Image returnImage = null;
try
{
MemoryStream ms = new MemoryStream(byteArrayIn);
returnImage = System.Drawing.Image.FromStream(ms); // parameter is invalid
}
catch (Exception ex)
{
string a = ex.ToString();
// Response.Write("sfdsfn");
}
return returnImage;
}
I did lot of search in Net but i cant get any useful answer for me?
any help..thanks in advance
Simple way Image.FromStream:
public Image byteArrayToImage(byte[] imgBytes)
{
using (MemoryStream imgStream = new MemoryStream(imgBytes))
{
return Image.FromStream(imgStream);
}
}
You can use new Bitmap(ms):
Image returnImage = null;
MemoryStream ms = new MemoryStream(byteArrayIn);
returnImage = new Bitmap(ms);
Similarly, you can use Bitmap.FromStream (oddly, I can't find documentation for it).
Took me 2 minutes to find this one :
ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(byteArray);
Using C#, I'm trying to load a JPEG file from disk and convert it to a byte array. So far, I have this code:
static void Main(string[] args)
{
System.Windows.Media.Imaging.BitmapFrame bitmapFrame;
using (var fs = new System.IO.FileStream(#"C:\Lenna.jpg", FileMode.Open))
{
bitmapFrame = BitmapFrame.Create(fs);
}
System.Windows.Media.Imaging.BitmapEncoder encoder =
new System.Windows.Media.Imaging.JpegBitmapEncoder();
encoder.Frames.Add(bitmapFrame);
byte[] myBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
encoder.Save(memoryStream); // Line ARGH
// mission accomplished if myBytes is populated
myBytes = memoryStream.ToArray();
}
}
However, executing line ARGH gives me the message:
COMException was unhandled. The handle is invalid. (Exception from
HRESULT: 0x80070006 (E_HANDLE))
I don't think there is anything special about the file Lenna.jpg - I downloaded it from http://computervision.wikia.com/wiki/File:Lenna.jpg. Can you tell what is wrong with the above code?
Check the examples from this article: http://www.codeproject.com/KB/recipes/ImageConverter.aspx
Also it's better to use classes from System.Drawing
Image img = Image.FromFile(#"C:\Lenna.jpg");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
arr = ms.ToArray();
}
Other suggestion:
byte[] image = System.IO.File.ReadAllBytes ( Server.MapPath ( "noimage.png" ) );
Should be working not only with images.
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
The reason this error happens is because the BitmapFrame.Create() method you are using defaults to an OnDemand load. The BitmapFrame doesn't try to read the stream it's associated with until the call to encoder.Save, by which point the stream is already disposed.
You could either wrap the entire function in the using {} block, or use an alternative BitmapFrame.Create(), such as:
BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);