i get an
A generic error occurred in GDI+
exception when I call img.Save(path, jpegCodec, encoderParams);
here
public ActionResult CropImage(string hdnx, string hdny, string hdnw, string hdnh)
{
string fname = "pool.jpg";
string fpath = Path.Combine(Server.MapPath("~/images"), fname);
Image oimg = Image.FromFile(fpath);
Rectangle cropcords = new Rectangle(
Convert.ToInt32(hdnx),
Convert.ToInt32(hdny),
Convert.ToInt32(hdnw),
Convert.ToInt32(hdnh));
string cfname, cfpath;
Bitmap bitMap = new Bitmap(cropcords.Width, cropcords.Height,img.PixelFormat);
Graphics grph = Graphics.FromImage(bitMap);
grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel);
cfname = "crop_" + fname;
cfpath = Path.Combine(Server.MapPath("~/cropimages"), cfname);
bitMap.Save(cfpath);
return Json("success",JsonRequestBehavior.AllowGet);
}
As long as the image object exists that was created by loading the image from the file, the file is in use. You can't save an image with the same name while the file is in use.
Instead of using Image.FromFile
to load the image, open a file stream and use Image.FromStream
to create the image, then close the file stream. That way the file is no longer in use, and you can replace it.