I am capturing images from a smart camera imager and receiving the byte array from the camera through socket programming (.NET application is the client, camera is the server).
The problem is that i get System.InvalidArgument exception at runtime.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream(byteArray);
return Image.FromStream(ms, false, false);
/*last argument is supposed to turn Image data validation off*/
}
return null;
}
I have searched this problem in many forums and tried the suggestions given by many experts but nothing helped.
I dont think there is any problem with the byte array as such because When i feed the same byte array into my VC++ MFC client application, i get the image. But this doesn't somehow work in C#.NET.
Can anyone help me ?
P.S :
Other methods i've tried to accomplish the same task are:
1.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream();
ms.Write(byteArray, 0, byteArray.Length);
ms.Position = 0;
return Image.FromStream(ms, false, false);
}
return null;
}
2.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap b = (Bitmap)tc.ConvertFrom(byteArray);
return b;
}
return null;
}
None of the above methods worked. Kindly help.
Image.FromStream() expects a stream that contains ONLY one image!
It resets the stream.Position to 0. I've you have a stream that contains multiple images or other stuff, you have to read your image data into a byte array and to initialize a MemoryStream with that:
Image.FromStream(new MemoryStream(myImageByteArray));
The MemoryStream has to remain open as long as the image is in use.
I've learned that the hard way, too.
Maybe the image is embedded in an OLE field and you have to consider the 88 bytes OLE header plus payload:
byteBlobData = (Byte[]) reader.GetValue(0);
stream = new MemoryStream(byteBlobData, 88, byteBlobData.Length - 88);
img = Image.FromStream(stream);
I'm guessing that something is going wrong when receiving the file from the server. Perhaps you're only getting part of the file before trying to convert it to an Image? Are you sure it's the exact same byte array you're feeding the C++ application?
Try saving the stream to a file and see what you get. You might be able to uncover some clues there.
You can also add a breakpoint and manually compare some of the bytes in the byte array to what they're supposed to be (if you know that).
Edit: It looks like there's nothing wrong with receiving the data. The problem is that it's in raw format (not a format that Image.FromStream understands). The Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) constructor may be of use here. Or, you can create the blank bitmap and blt it manually from the raw data.
I've had this problem when doing this:
MemoryStream stream = new MemoryStream();
screenshot.Save(stream, ImageFormat.Png);
byte[] bytes = new byte[stream.Length];
stream.Save(bytes, 0, steam.Length);
With the last 2 lines being the problem. I fixed it by doing this:
MemoryStream stream = new MemoryStream();
screenshot.Save(stream, ImageFormat.Png);
byte[] bytes = stream.ToArray();
And then this worked:
MemoryStream stream = new MemoryStream(bytes);
var newImage = System.Drawing.Image.FromStream(stream);
stream.Dispose();
System.InvalidArgument means The stream does not have a valid image format, i.e. an image type that is not supported.
Try this:
public Image byteArrayToImage(byte[] item)
{
Image img=Image.FromStream(new MemoryStream(item));
img.Save(Response.OutputStream, ImageFormat.Gif);
return img;
}
Hope it helps!
I've had the same problem in the past and it was caused by a leak within the windows GDI libraries, which is what 'Bitmap' uses. If this happening all the time for you then its probably unrelated, however.
this code is working
string query="SELECT * from gym_member where Registration_No ='" + textBox9.Text + "'";
command = new SqlCommand(query,con);
ad = new SqlDataAdapter(command);
DataTable dt = new DataTable();
ad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
textBox2.Text = dt.Rows[0][2].ToString();
byte[] img = (byte[])dt.Rows[0][18];
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
ms.Dispose();
Try to use something similar to what is described here https://social.msdn.microsoft.com/Forums/vstudio/en-US/de9ee1c9-16d3-4422-a99f-e863041e4c1d/reading-raw-rgba-data-into-a-bitmap
Image ImageFromRawBgraArray(
byte[] arr,
int charWidth, int charHeight,
int widthInChars,
PixelFormat pixelFormat)
{
var output = new Bitmap(width, height, pixelFormat);
var rect = new Rectangle(0, 0, width, height);
var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);
// Row-by-row copy
var arrRowLength = width * Image.GetPixelFormatSize(output.PixelFormat) / 8;
var ptr = bmpData.Scan0;
for (var i = 0; i < height; i++)
{
Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength);
ptr += bmpData.Stride;
}
output.UnlockBits(bmpData);
return output;
}
After load from DataBase byteArray has more byte than one image. In my case it was 82.
MemoryStream ms = new MemoryStream();
ms.Write(byteArray, 82, byteArray.Length - 82);
Image image = Image.FromStream(ms);
And for save in the DB I insert 82 byte to begin stream. Properties.Resources.ImgForDB - it is binary file that contain those 82 byte. (I get it next path - Load Image from DB to MemoryStream and save to binary file first 82 byte. You can take it here - https://yadi.sk/d/bFVQk_tdEXUd-A)
MemoryStream temp = new MemoryStream();
MemoryStream ms = new MemoryStream();
OleDbCommand cmd;
if (path != "")
{
Image.FromFile(path).Save(temp, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Write(Properties.Resources.ImgForDB, 0, Properties.Resources.ImgForDB.Length);
ms.Write(temp.ToArray(), 0, temp.ToArray().Length);
cmd = new OleDbCommand("insert into Someone (first, Second, Third) values (#a,#b,#c)", connP);
cmd.Parameters.AddWithValue("#a", fio);
cmd.Parameters.AddWithValue("#b", post);
cmd.Parameters.AddWithValue("#c", ms.ToArray());
cmd.ExecuteNonQuery();
Related
I created local server, that should get image files as binary data and save them back as images in hard drive.
Socket mySocket = myListener.AcceptSocket();
#region Connection Check
if (mySocket.Connected)
{
============
/* Some Code For Displaying Information*/
============
byte[] data = new byte[mySocket.ReceiveBufferSize];
int i = mySocket.Receive(data, data.Length, 0);
byteArrayToImage(data);
mySocket.Close();
}
byteArrayToImage method Converts byte Array to Image file and saves on hard drive, here's the code
public void byteArrayToImage(Byte[] data)
{
MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);
img.Save(#"C:\MyPersonalwebServer\ImageData\img.png", ImageFormat.Png);
}
but I get ArgumentException here: Image img = Image.FromStream(ms)
Here is part of data array: http://s43.radikal.ru/i101/1403/78/1913ab884790.png
Any ideas how to fix it?
Thanks in advance.
The following code works for me:
var buffer = new byte[256];
FileStream fs = new FileStream(#"D:\test.png", FileMode.Open);
var ms = new MemoryStream();
int readCtr;
while ((readCtr = fs.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, readCtr);
}
Image img = Image.FromStream(ms);
img.Save(#"D:\test2.png", ImageFormat.Png);
Are you sure that the data you are sending from the client connection is complete/clean?
Make sure the data you are sending from the client isn't appending null bytes when performing Socket.Send(), or try clean it up server-side by stripping any null bytes from the end of the byte array:
buffer = buffer.Where(x => x != (byte)0).ToArray();
You could also check the size of the image manually against the content received server-side using standard debug practices/console output.
Either way, I dont think your code would be failing if the byte array had valid content.
I am trying to convert bitmap Image to Byte array. I have select all the image by using MediaLibrary class and added it into a list of bitmap images. Here is my code
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
for (int i = 0; i < imgname.Count(); i++)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(ms, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
bytes = ms.GetBuffer();
stream.Write(bytes, 0, bytes.Length);
}
// byte[] bytes = Encoding.UTF8.GetBytes(imgname[i]);//new byte[ImgCollection[i].PixelWidth * ImgCollection[i].PixelHeight * 4];
// stream.Write(bytes, 0, bytes.Length);
}
}
}
else {
directory = true;
}
}
Basically what I am trying to do is, selecting all images or photo from device and create a zip file of that images. I was successful in creating a zip file of images. When I extract that file there is some images, but the problem is when I double click on image, I can't see that image. I think the problem is in reading the bytes of image. I am not getting what's wrong? Is my code is correct ?
Perhaps you can try the below. I know this code maintains the image, so if you have no luck using this, you may have a different issue.
// Convert the new image to a byte[]
ImageConverter converter = new ImageConverter();
byte[] newBA = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
The ImageConverter is of the System.Drawing namespace.
Update:
http://msdn.microsoft.com/en-GB/library/system.windows.media.imagesourceconverter.convertto.aspx
You should be able to use this in place of the System.Drawing type I suggested.
There is no need to save the WriteableBitmap to a MemoryStream and then copy it to an IsolatedStorageFileStream. Just save the bitmap directly to the IsolatedStorageFileStream.
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
}
This will allow you to save on memory as well. If you really want to save memory, you could reuse the WriteableBitmap.
I have the following code to convert image to base64:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
StreamResourceInfo sri = null;
Uri uri = new Uri("Checked.png", UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
base64 = System.Convert.ToBase64String(imageBytes);
}
And the following code to get Bitmap image form base 64:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So when i convert and deconvert it is blank.
I know that deconverter works, because, when i give him exact string:
string base64="iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAQAAABLCVATAAACH0lEQVR42q3WoZKrMBQGYGRkIpHEoY9DMrh1nUGtzxPcGV7gCsTaK3iBCqa2ipmrVqLrWrmytjL3nBwoEGD30ja/6JaSj/wp3SEIXjpUoB+Oeg0zpoR+NsyoDVOgi39cbYHAy4MQTc0wOYZepxRBUkn9UxxEiNnXxyYwd6w/438hSddHJilv1tqv664Shle1DeJaJihPV9uNQ+NWBRK2QVSr+GjtaFzOIpdjKFShnoY+Gv0N0u0OVLexY48NQ+68JchdpQu/o1piVMu6faJdwjNWIAYyl55bqGUtbndO53TzCIpUpCkdlEm+V3J3Ir8r3uops2+FkTmvx832IGJwN97xS/5Ti0LQ/WLwtbxMal2ueAwvc2c8CAgSJip5U4+tKHECMlUzq2UcA9EyROuJi6/71dtzWAfVcq0Jw1CsYh13kDDteVoirE+zWtLVinQ8ZAS5YlVlvRHWfi3pakUQL0OOwmp/W/vN6Gt5zBIkzEezxnCtMJsxDIECTYmhp3bej4HHzaalNMyAnzE0UBKp6Z1Do2pwd3JkAH6CxlTs/bZOZ661yMwhohDLQqREMWz8UAvWoUQleggehG5dSPUbv28GJlnKHGJsqPi7vuG/MGTyCGslOtkCOayrGOa/indajdudb6FUpXoepgiLHIIMriddyzrkMBhGAqlOH4U2hKCT2j0NdU8jFbzpZ3LQlh9srPqEQ1Y9lEP2CVa99KHvH8mnrGGdl9V9AAAAAElFTkSuQmCC";
Which is my Checked.png converted in online converter. It decompreses perfectly.
And this is my base64, which i get by converting:
"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"
My problem is that string which i get as base64 from my code - is incorrect *What i did wrong?*
What about trying:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes))
{
Image streamImage = Image.FromStream(ms);
context.Response.ContentType = "image/jpeg";
streamImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
return streamImage;
}
}
I agree with Alexei that your code for reading the image in does look a little strange. I've recently written some code for a similar task that I was doing which might point you in the right direction:
string fileContent = null;
/* Check the file actually has some content to display to the user */
if (uploadFile != null && uploadFile.ContentLength > 0)
{
byte[] fileBytes = new byte[uploadFile.ContentLength];
int byteCount = uploadFile.InputStream.Read(fileBytes, 0, (int)uploadFile.ContentLength);
if (byteCount > 0)
{
fileContent = CreateBase64Image(fileBytes);
}
}
private string CreateBase64Image(byte[] fileBytes)
{
Image streamImage;
/* Ensure we've streamed the document out correctly before we commit to the conversion */
using (MemoryStream ms = new MemoryStream(fileBytes))
{
/* Create a new image, saved as a scaled version of the original */
streamImage = ScaleImage(Image.FromStream(ms));
}
using (MemoryStream ms = new MemoryStream())
{
/* Convert this image back to a base64 string */
streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
}
not an answer: more of a long comment ... OP states that decoding code works perfectly fine, also it looks suspicios. Also code assumed to be verified to work on PNG images, but saving code explicitly produces valid JPG with SaveJpeg call...
Your code that creates stream for reading looks strange - you create stream over existing byte array, than write the same bytes into that stream, and that pass that stream without seeking back to 0 to some method.
Potential fix (assuming BitampImage can accept JPG stream):
don't call Write at all as stream already have the bytes you want
set ms.Position = 0 after writing to the stream.
Note: I'm not sure if it is OK to dispose stream that is a source for BitmapImage, you may need to remove using too.
I'm trying to do image processing on wp7,
and now i finished convertImagetoBytes and convertByteToBitmapImage.
I suppose I can change the values in the byte array to do some image processing work,
but it turns out to be a black image in the picturebox.
(Now I just wanna process .jpg images)
convertImagetoBytes
byte[] data = null;
using (MemoryStream stream = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
data = stream.GetBuffer();
}
convertBytestoImage
MemoryStream stream = new MemoryStream(bytes);
stream.Position = 0;
BitmapImage bi = new BitmapImage();
bi.SetSource(stream);
return bi;
now if i change the values in the byte array,just like this(grayscale)
for (int i = 0; i < bytesCount; i+=4)
{
colorTemp = data[i+2];
data[i+1 ] =data[i+2]= data[i + 3] = (byte)colorTemp;
}
the image turns out to be black.
You've saved it as a JPEG - but you appear to be trying to change it as if it were raw data. You can't just mess around with the data of a JPEG file to fake greyscale.
By the way, you should use stream.ToArray instead of stream.GetBuffer() as the latter will usually be larger than the real data.
You should also look into using René Schulte's WriteableBitmapEx library.
And consider reading this article about a Windows Phone Picture Effects Application
I'm trying to convert a byte array to a bitmap but it always shows me:
System.ArgumentException: Parameter is not valid.
My code is as follows:
I'm passing the bytes through a webservice with:
string DecodedString = string.Empty;
DecodedString = System.Text.Encoding.GetEncoding(1251).GetString(bytes);
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
and in my webPage:
byte[] bytes = (Byte[])System.Text.Encoding.GetEncoding(1251).GetBytes(XmlConvert.DecodeName(xDocument.SelectSingleNode("Response/Images/Photo").InnerText));
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);//(System.Drawing.Image.FromStream(ms));
Try passing the string as a Base64:
string DecodedString = string.Empty;
DecodedString = System.Convert.ToBase64String(bytes)
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
...
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = System.Drawing.Image.FromStream(ms);
You also won't need to use XmlConvert to encode/decode the string.
I did it, with the help of all of you, here is my page code
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms); //(Bitmap)System.Drawing.Image.FromStream(ms);
System.Drawing.Imaging.FrameDimension frameDim;
frameDim = new System.Drawing.Imaging.FrameDimension(b.FrameDimensionsList[0]);
int NumberOfFrames = b.GetFrameCount(frameDim);
string[] paths = new string[NumberOfFrames];
for (int i = 0; i < NumberOfFrames; i++)
{
b.SelectActiveFrame(frameDim, i);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(b);
paths[i] = imagePathfile.Remove(imagePathfile.Length - 4, 4) + i.ToString() + ".gif";
bmp.Save(paths[i], System.Drawing.Imaging.ImageFormat.Gif);
//bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
bmp.Dispose();
}
Image1.Src = paths[0];
//Check if there's more than 1 image cause its a TIFF
if (paths.Length>1)
{
Image2.Src = paths[1];
}
I had a similar problem recently, but using Silverlight. I ended up needing to create a Custom HTTP Handler in order to pass the byte[] that defined the image back as a stream.
See http://www.dotnetcurry.com/ShowArticle.aspx?ID=220
Edit: This allows you to avoid worrying about XML encoding, and passes the image back in Binary form... YMMV
According to MSDN:
ArgumentException - The stream does not have a valid image format
I believe your problem is in the original byte[] array you are passing to the web service.
According to one of your comments, you did:
System.IO.FileStream fs = new System.IO.FileStream(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
int streamLength = Convert.ToInt32(fs.Length);
bytes = new byte[streamLength];
fs.Read(bytes, 0, streamLength);
fs.Read returns the number of bytes that have been read into the byte array; it doesn't always read the entire file!
Try using the StreamFile method from http://www.dotnetspider.com/resources/4515-convert-file-into-byte-array.aspx. (First result of Google search)
Try this:
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(bytes) as Image;
System.Drawing.Bitmap b = new System.Drawing.BitMap(image);
EDIT
Take a look at this:
Transfer any files on Web services by c#
actually i had been meet this problem, In my case, when i use IE browser, it is ok but when use another browser it always have the same error.
"Parameter is not valid exception is always happening in the same line of code:
System.Drawing.Image.FromStream(ms));"
So i think it seems this issue depend on browser and type of image (JPEG,JPEG2000).
Here is some code I used converting bytes to an image for a unit test:
protected override Image LoadImage()
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
To my understanding, the image can not be shown because the format of the image's bytes is not correct. Every image format has its own head or something.