Tuesday, December 12, 2006

How to convert Image in Binary Stream/Byte array

Following code explains how to get an image from a website as stream and convert it to byte array. Then from byte array to System.Drawing.Image.

The important thing to notice is, when we get stream from web, it gives error in getting length of the stream. The helper method gets the length and convert the stream to byte array.

Following is the code:


private void buttonProcess_Click(object sender, EventArgs e)
{
string url = @"http://localhost:1137/WebSiteImage/TestImage.jpg";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
byte[] byteData;
using (Stream stream = response.GetResponseStream())
{
byteData = ReadStream(stream, 1000);
}
using (MemoryStream mStream = new MemoryStream(byteData))
{
Image image = Image.FromStream(mStream);
this.pictureBoxTest.Image = image;
}
}


private byte[] ReadStream(Stream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte == -1)
{
return buffer;
}
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
byte[] bytes = new byte[read];
Array.Copy(buffer, bytes, read);
return bytes;
}