Image Uploading in ASP.NET using C#

This is way I’m trying to explain an image uploading in asp.net using C#.

Here is I’m going to post image in to an url with image byte array. On there a page will save that image byte array in to image in given path.

POST IMAGE

As I mentioned above, the following method is going to use post image.

using System.Net;
using System.Text;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;


private void postImage()
{

HttpWebRequest request;
request = (HttpWebRequest)HttpWebRequest.Create("url");
request.KeepAlive = true;
request.Method = "POST";
byte[] byteArray = ConvertImageToByteArray((System.Drawing.Image)new Bitmap(@"C:\test.jpg"), ImageFormat.Jpeg);
request.ContentType = "image/JPEG";
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
}

private static byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert,ImageFormat formatOfImage)
{
byte[] Ret;
try
{

using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, formatOfImage);
Ret = ms.ToArray();
}
}
catch (Exception) { throw; }

return Ret;
}

From above the method postImage() will post the image in to given url as byte array. And the method ConvertImageToByteArray(System.Drawing.Image imageToConvert,ImageFormat formatOfImage) will help us for getting byte array from an image.

UPLOAD IMAGE

The following code will help us save the image….

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Text;


protected void Page_Load(object sender, EventArgs e)
{

try
{
string dirPath = Server.MapPath("Asset") + "\\" ;
Guid imgId = Guid.NewGuid();
string imgPath = dirPath + "\\" + imgId.ToString() + ".jpg";
Response.ContentType = "image/JPEG";
System.Drawing.Image img = Bitmap.FromStream(Page.Request.InputStream);
img.Save(imgPath, ImageFormat.Jpeg);
}
catch { }
}

That's it....

...S.VinothkumaR.

2 comments:

Unknown said...

Change the following:

dirPath + "\\" + imgId.ToString() + ".jpg";

to

dirPath + imgId.ToString() + ".jpg";

dirPath already ends with "\\"

Mark Paul said...

I own you a HUGE thanks mate!

I was doing this exact same thing for an image uploaded API I was building and kept getting a exception when trying to read the Response.


I made a very basic (yet critical) error by not setting
request.ContentType = "image/JPEG";

as i though that if you send in a Byte Array this should have been enough:

request.ContentType = "application/x-www-form-urlencoded";

But this caused a WebException with no exception details so I had no idea which line was causing the error!

It works now and a big thanks for sharing your knowledge!