473,513 Members | 2,378 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# MemoryStream to Image problem

Ben
Hello,

I'm trying to get an image from a webserver here in the network. I
managed to create a socket connection and filter out the response
headers. I load the body of the reply into a MemoryStream, but when
trying to use Image.FromStream(), I get an invalid argument error.

Here is my code:

public Image loadImage(DateTime time)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
sock.Connect("192.168.1.12", 80);

string year = curdate.Year.ToString();
year = year.Substring(year.Length - 2);
string month = curdate.Month.ToString().PadLeft(2, '0');
string day = curdate.Day.ToString().PadLeft(2, '0');

string header = "GET /garfield/garfield_coll/ga" + year +
month + day + ".gif HTTP/1.0\r\n";
header += "Host: 192.168.1.12\r\n\r\n";

textBox1.Text = "Sending request:\r\n\r\n" + header + "?";

sock.Send(Encoding.ASCII.GetBytes(header));
textBox1.Text += ("Request sent...\r\n");

byte[] bbuffer = new byte[sock.ReceiveBufferSize];

sock.Receive(bbuffer);
textBox1.Text += ("Reply received...\r\n");

MemoryStream mstream;

char[] reply = Encoding.ASCII.GetChars(bbuffer);
string replystr = new string(reply);

Regex rg = new Regex("\\r\\n\\r\\n");
MatchCollection mc = rg.Matches(replystr);
int i = mc[0].Index;

mstream = new MemoryStream();
mstream.Write(bbuffer, i, bbuffer.Length - i);
sock.Disconnect(false);
return Image.FromStream(mstream);
}

Does anybody have any ideas on how to solve this?

Thanks,

Ben
Jun 23 '07 #1
4 11530
"Ben" <el*****@gmail.comwrote in message
news:Or**************@TK2MSFTNGP02.phx.gbl...
I'm trying to get an image from a webserver here in the network. I managed
to create a socket connection and filter out the response headers. I load
the body of the reply into a MemoryStream, but when trying to use
Image.FromStream(), I get an invalid argument error.
[...]
Does anybody have any ideas on how to solve this?
I don't know what's wrong with your code, but I have a suggestion: Why
don't you use an HttpWebRequest, and then assign the ResponseStream to the
Image.FromStream? It's much shorter and easier to understand. I have used t
before and works very well.

HttpWebRequest req= (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp= (HttpWebResponse)req.GetResponse();
Stream stm = resp.GetResponseStream();
System.Drawing.Image img = new Bitmap(stm);
stm.Close();

Jun 23 '07 #2
On Sat, 23 Jun 2007 13:53:01 -0700, Ben <el*****@gmail.comwrote:
I'm trying to get an image from a webserver here in the network. I
managed to create a socket connection and filter out the response
headers. I load the body of the reply into a MemoryStream, but when
trying to use Image.FromStream(), I get an invalid argument error.
I see two problems, both fatal. For one, you don't account for the length
of the string you're searching for, so the "\r\n\r\n" substring you've
found is still included in the MemoryString you're trying to use to
initialize the Image. Of course, that's not a valid set of bytes for the
beginning of an Image, so it fails.

The other problem is that you are not doing anything to ensure that you've
received all of the data for the image. For any image of any significant
size, you aren't going to get all of the data in a single call to
Socket.Receive(). You need to keep calling it and adding the data to the
MemoryStream until you've reached the end of the data (the header should
tell you how many bytes to expect, if I recall correctly), and only then
try to create an Image from it.

Either of those problems alone would prevent you from correctly creating
an Image. You need to fix both in order for your code to be reliable.

Pete
Jun 23 '07 #3
Ben
Thank you both :)

I'm new to the sockets thing, and don't quite understand it yet.
I will try Alberto's suggestion.

Ben
Jun 23 '07 #4
The WebClient class in System.Net provides very simple methods to do this,
even simpler than HttpWebRequest/ Response:

WebClient wc = new WebClient();
Stream s = wc.OpenRead("urltoresource");

You could also use the DownloadData method, and wrap a MemoryStream around
the resultant byte array.

--Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net


"Ben" wrote:
Hello,

I'm trying to get an image from a webserver here in the network. I
managed to create a socket connection and filter out the response
headers. I load the body of the reply into a MemoryStream, but when
trying to use Image.FromStream(), I get an invalid argument error.

Here is my code:

public Image loadImage(DateTime time)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
sock.Connect("192.168.1.12", 80);

string year = curdate.Year.ToString();
year = year.Substring(year.Length - 2);
string month = curdate.Month.ToString().PadLeft(2, '0');
string day = curdate.Day.ToString().PadLeft(2, '0');

string header = "GET /garfield/garfield_coll/ga" + year +
month + day + ".gif HTTP/1.0\r\n";
header += "Host: 192.168.1.12\r\n\r\n";

textBox1.Text = "Sending request:\r\n\r\n" + header + "?";

sock.Send(Encoding.ASCII.GetBytes(header));
textBox1.Text += ("Request sent...\r\n");

byte[] bbuffer = new byte[sock.ReceiveBufferSize];

sock.Receive(bbuffer);
textBox1.Text += ("Reply received...\r\n");

MemoryStream mstream;

char[] reply = Encoding.ASCII.GetChars(bbuffer);
string replystr = new string(reply);

Regex rg = new Regex("\\r\\n\\r\\n");
MatchCollection mc = rg.Matches(replystr);
int i = mc[0].Index;

mstream = new MemoryStream();
mstream.Write(bbuffer, i, bbuffer.Length - i);
sock.Disconnect(false);
return Image.FromStream(mstream);
}

Does anybody have any ideas on how to solve this?

Thanks,

Ben
Jun 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4533
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in...
1
5551
by: Arcnet | last post by:
Using MemoryStream I Have a problem to create a new Image from byte array that originaly was created from an older image (Everything is being preformed in the same Thread) //Get Image...
3
5856
by: T. Davis | last post by:
In C#, I am able to successfully stream a TIFF image that comes from a BLOB field in a database, save it to file, then convert the pages within TIFF file into jpegs (using GDI+) and display on the...
7
2389
by: Robson Carvalho Machado | last post by:
Does anyone knows how to CAST this SQL Response into a MemoryStream ?? When executing below code an error message says "Specified cast is not valid" I need to put this into MemoryStream to use it...
10
4531
by: LoSTMaN | last post by:
Hi, I try to make a DragDrop to a Picturebox, to drag images from IE. But i'm stuck here : If (e.Data.GetDataPresent("DeviceIndependentBitmap")) Then PictureBox1.Image =...
4
10575
by: vbdotnetmania | last post by:
I have the following snippet of code with bm being a succesfully stored bitmap (not including all the code just the relevant bits) Dim g As Graphics Dim g2 As Graphics Dim bm As Bitmap Dim bm2...
2
16020
by: Bruce D | last post by:
I'm having a problem saving my bitmap in my MySQL database. Apparently it's too big...but it shouldn't be. Here's what I got: Dim bmpDocument As Bitmap = Bitmap.FromHbitmap(hDibCopy) ' get...
13
2832
by: Don | last post by:
When I run the following code, the MemoryStream's Position is always set to 762 instead of 0, which is what I would expect: Dim bmp As Image Dim ms As MemoryStream bmp = New...
3
2100
by: Neeraj | last post by:
hi i am working on dicom image.this is code which gives exception on "System.Drawing.Image imgInFile = System.Drawing.Image.FromStream(new System.IO.MemoryStream(destPixels ) " ..The exception is...
0
7267
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7175
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7120
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7542
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5697
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3235
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1609
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
466
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.