I'm trying to upload an image with an ASP fileupload control but crop it into a square from the middle. this is my code,
public void CropImage(string imagePath)
{
//string imagePath = @"C:\Users\Admin\Desktop\test.jpg";
Bitmap croppedImage;
int x, y;
// Here we capture the resource - image file.
using (var originalImage = new Bitmap(imagePath))
{
if (originalImage.Width > originalImage.Height) {
x = 0;
y = (originalImage.Width / 2) - (originalImage.Height / 2);
}
else if (originalImage.Width < originalImage.Height)
{
y = 0;
x = (originalImage.Height / 2) - (originalImage.Width / 2);
}
else {
y=x=0;
}
int sqrWidth = (originalImage.Width >= originalImage.Height) ? originalImage.Height : originalImage.Width;
Rectangle crop = new Rectangle(x, y, sqrWidth, sqrWidth);
// Here we capture another resource.
croppedImage = originalImage.Clone(crop, originalImage.PixelFormat);
} // Here we release the original resource - bitmap in memory and file on disk.
// At this point the file on disk already free - you can record to the same path.
croppedImage.Save(imagePath, ImageFormat.Jpeg);
// It is desirable release this resource too.
croppedImage.Dispose();
}
//Updates an agent in the database.
protected void BtnUpdate_Click(object sender, EventArgs e)
{
AgentController agentController = new AgentController();
AgentContactController agentContactController = new AgentContactController();
CityController cityController = new CityController();
DistrictController districtController = new DistrictController();
ProvinceController provinceController = new ProvinceController();
CountryController countryController = new CountryController();
InsurancePortalContext context = new InsurancePortalContext();
string folderPath = Server.MapPath("~/AdvisersImages/");
//Check whether Directory (Folder) exists.
if (!Directory.Exists(folderPath))
{
//If Directory (Folder) does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
//Save the File to the Directory (Folder).
string FilePath = folderPath + Path.GetFileName(ImageUploadUpdate.PostedFile.FileName);
if (!File.Exists(FilePath))
{
ImageUploadUpdate.SaveAs(FilePath);
CropImage(FilePath);
}
but I'm getting the out of memory exception at,
croppedImage = originalImage.Clone(crop, originalImage.PixelFormat);
If I don't use the x,y value setting conditional block in CropImage function and/or only save the uploaded image as is, this exception doesn't come.
thanks in advance