bind an image in c# using byte array - asp.net

protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string ext = Path.GetExtension(filename);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;
}
else
{
Response.Write("<script>alert('unsupported format of photo file');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}

Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;
This code is working well ..

I assume you are trying to display image with base64 string in an System.Web.UI.WebControls.Image.
first, create a client JavaScript function to set src attribute of your <img /> tag:
function setImageData(imageBase64) {
document.getElementById("imageId").src = "data:image/png;base64," + imageBase64;
}
then, Invoke that method by
Response.Write("<script>setImageData("+ base64String +")</script>");

I would recommend you to create ImageHandler (inherited from IHttpHandler), register it in the web.config file, and modify your Button2_Click function:
public void Button2_Click(object sender, EventArgs e)
{
...
Image1.ImageUrl = "URL_TO_IMAGE_HANDLER.jpg";
...
}
You can read about http-handlers here: http://www.codeproject.com/Articles/34084/Generic-Image-Handler-Using-IHttpHandler
This solution is much better than Base64 approach, it's also possible to implement caching support here

See this Tutorial you can use byte array to get images
UPDATE: By the way you should use this function :
string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
using ( var imageStream = new MemoryStream( imageBytes, false ) )
{
Bitmap image = new Bitmap( imageStream );
}
Edit
You can convert base64string to image by Image.FromStream. You will need to convert the base64string to stream first.
byte[] imageBytes = Convert.FromBase64String(imgBase64String);
MemoryStream ms1 = new MemoryStream(imageBytes);
Image img = Image.FromStream(ms1);

I have just solved this question..this is the updated code..
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string ext = Path.GetExtension(filename);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," + base64String;
}
else
{
Response.Write("<script>alert('unsupported format of photo file');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}

Related

how can i upload file to server in asp.net

I have 2 pages send.aspx and recive.aspx.
In send.aspx, I have FileUpload and Button that send selected file to recive.aspx page.
In below you can see recive.aspx.cs code in Page_Load
at the end .
How can I send file to this page?
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if (action == null)
{
Response.StatusCode = 400;
Response.End();
}
if (action.Equals("upload"))
{
HttpPostedFile file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
//string guid = Guid.NewGuid().ToString();
string ext = Path.GetExtension(file.FileName);
//2- Get and check file extension
string[] validExtesions = { ".e", ".jpg", ".gif", ".png", ".rar",
".zip",".3gp",".3gpp",".mp4",".mov",".wmv",".avi", "",".jpeg", ".mp3", ".ogg"};
if (Array.IndexOf(validExtesions, ext.ToLower()) < 0)
{
Response.Write("Invalid file extension!");
Response.End();
}
//3- Get and check file size
long fileSize = file.ContentLength;
fileSize /= 1024;
if (fileSize > 2048000)
{
Response.Write("Fiele size must be < 2GB");
Response.End();
}
//4- Get file name
string fileName = Path.GetFileName(file.FileName);
//5- Check file exist and if (true) generate new name
while (File.Exists(Path.Combine(UploadFolder, fileName)))
fileName = "1" + fileName;
string fname = fileName;
string path = Server.MapPath(Path.Combine(UploadFolder, fname));
file.SaveAs(path);
Response.Write(fname);
Response.End();
}
else
{
Response.StatusCode = 400;
Response.End();
}
}
}

Grid View Row Data Bound event

I can't run on IIS Server. I write with dynamically create link button in gridvew row data bound and Link button can't redirect access to file server. I only can on visual studio. Please let me know, how to solve it.
protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.`enter code here`RowType == DataControlRowType.DataRow)
{
string variable = e.Row.Cells[8].Text.ToString();
string[] stringSeparators = { ";" };
string[] result;
result = variable.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = new LinkButton();
lb.Text = s.ToString() + "<br />";
lb.CommandName = "ApproveVacation";
lb.Command += LinkButton_Command;
e.Row.Cells[8].Controls.Add(lb);
}
}
}
}
protected void LinkButton_Command(object sender, CommandEventArgs e)
{
string val = ((LinkButton)sender).Text;
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
if (row == -1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
return;
}
GridViewRow gdrow = GridView1.Rows[row];
DataRow dr = ((DataTable)this.GridView1.DataSource).Rows[gdrow.DataItemIndex];
if (e.CommandName == "ApproveVacation")
{
try
{
string username = "Bla";
string password = "bla";
System.Net.NetworkCredential readCredentials = new NetworkCredential(username, password);
string filepath = #"\\192.168.1.100\SAPAttachments\abc";
using (new NetworkConnection(filepath, readCredentials))
{
WebClient User = new WebClient();
string file = ((LinkButton)sender).Text;
string a = #"<br />";
file = file.Replace(a, "");
foreach (var item in file)
{
Byte[] FileBuffer = User.DownloadData(file);
string stringCutted = file.Substring(file.LastIndexOf(".") + 1);
if (stringCutted == "docx" || stringCutted == "DOCX")
{
if (FileBuffer != null)
{
Context.Response.Clear();
FileInfo Sourcefile = new FileInfo(file);
Context.Response.ContentType = "Application/msword";
Context.Response.AppendHeader("Content-Disposition", "inline; filename=" + Sourcefile.Name);
Context.Response.AppendHeader("Content-Length", Sourcefile.Length.ToString());
Context.Response.WriteFile(Sourcefile.FullName);
Context.Response.End();
}
}
if (stringCutted == "pdf" || stringCutted == "PDF")
{
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
if (stringCutted == "jpg" || stringCutted == "JPG" || stringCutted == "jpeg" || stringCutted == "JPEG")
{
if (FileBuffer != null)
{
Response.ContentType = "image/jpeg";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Success');", true);
}
}
catch
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
}
}
}

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

Error reading words in the text file

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!
Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

Web Application not able to Delete files for Read/Write Enabled Folders in ASP.NET

When I'm trying to delete the images uploaded by me via website named "SampleApplication" I can see the following error shown in Stack Trace
The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +9723350
System.IO.File.Delete(String path) +9545728
SampleApplication.BasePage.DeleteApp_ImagesById(DataTable dt) +503
SampleApplication.PostLease.MyAccount.DeleteAd_Property(Object sender, EventArgs e) +193
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
The folder App_Images has been given Read/write Permission and inherits to child folders namely myfolder1, myfolder2, myfolder3, myfolder4. Even when I tried to forcefully delete the image eKuK2511.png from the FTP File manager it is showing the following error:
550 The process cannot access the file because it is being used by another process.
How to getrid of this error?
Edit:
Upload Code:
public void UploadImages()
{
if (ServerSideValidation() == true)
{
string SavePath;
ImgPaths = new List<string>();
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
if (hfc.Count > 0)
{
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
#region trials compression.
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + GetUniqueKey() + GetFileExtension(hpf.FileName);
SaveImageByCompressing(hpf, SavePath);
#endregion
//SavePath can be saved in DB.
ImgPaths.Add(SavePath);
//Save Thumbnail Image.
if (i == 0)
{
string savedName = "Thumb_" + GetUniqueKey() + GetFileExtension(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "\\").Replace("/", "\\"));
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + savedName;
SaveThumbImage(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "").Replace("/", "\\"), AppDomain.CurrentDomain.BaseDirectory + "App_Images\\" + Session["AppContext"].ToString() + "\\" + savedName, 75, 75);
ImgPaths.Add(SavePath);
}
}
}
Session.Remove("AppContext");
lblMsg.Text = "Images Uploaded Successfully.";
//ShowUploadedImages(ImgPaths);
}
else
{
lblMsg.Text = "Images uploaded are either in wrong format or were deleted after uploading.";
}
}
else
{
lstPaths = new List<string>();
lblMsg.Text = "No Images Uploaded";
}
}
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
Image imgFromClient = Image.FromStream(hpf.InputStream);
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width, imgFromClient.Height, myCallbackCompressed, IntPtr.Zero);
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public static void SaveThumbImage(string imagePath, string filePath, int width = 0, int height = 0)
{
Image originalImage = Image.FromFile(imagePath);
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave = originalImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private static bool ThumbnailCallback() { return false; }
private bool ServerSideValidation()
{
string errorMsg = string.Empty, temp = null;
bool errorFlag = true;
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.FileName!=String.Empty)
{
temp = ValidateImage(hpf);
if (temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
temp = null;
}
}
else
{
return false;
}
}
if (!string.IsNullOrWhiteSpace(errorMsg))
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}
private string GetFileExtension(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Extension;
}
private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}
private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return Session["AppContext"].ToString() + Page.User.Identity.Name.ToString() + result.ToString();
}
private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;
//6MB
int FileMaxSize = 6291456;
//Check Length of File is Valid or Not.
if (myFile.ContentLength > FileMaxSize)
{
msg = msg + "File Size is Too Large. You are allowed only a maximum of 6MB per Image.";
}
//Check File Type is Valid or Not.
if (!IsValidFile(myFile.FileName))
{
msg = msg + "Invalid File Type.";
}
return msg;
}
private bool IsValidFile(string filePath)
{
bool isValid = false;
string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.ToUpper().Contains(fileExtensions[i]))
{
isValid = true; break;
}
}
return isValid;
}
Delete Code:
/// <summary>
/// Delete all images. If there are no Images then by default NoImage.png is assigned. So skip deleting that image.
/// </summary>
/// <param name="dt"></param>
protected void DeleteApp_ImagesById(DataTable dt)
{
if (dt.Rows[0][0].ToString() != "~/images/NoImage.png")
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[0][i].ToString() != string.Empty)
{
string str = Regex.Replace(dt.Rows[0][i].ToString(), "~/", "");
File.Delete(Request.PhysicalApplicationPath.ToString() + Regex.Replace(str, "/", "\\").ToString());
}
}
}
}
The docs on MSDN about Image.Save say that the file remains locked until the Image is disposed.
So I suppose that changing the code that save the images in this way
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
using(Image imgFromClient = Image.FromStream(hpf.InputStream))
{
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory +
filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width,
imgFromClient.Height, myCallbackCompressed, IntPtr.Zero))
{
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public static void SaveThumbImage(string imagePath, string filePath,
int width = 0, int height = 0)
{
using(Image originalImage = Image.FromFile(imagePath))
{
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave = originalImage.GetThumbnailImage(width, height,
myCallback, IntPtr.Zero))
{
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
is a safe way to ensure your images are immediately unlocked when you finish with the upload code

Resources