title: Saving jpeg - The process cannot access the file because it is being used by another process?
body: <p>I'm trying to crop a jpeg file using the (x,y) coordinates,width and height and save the output in the same location(i.e replace). I tried the below code but its not working.</p>
  
  <pre><code>public void CropImage(int x, int y, int width, int height)
  {
  
  string image_path = @"C:\Users\Admin\Desktop\test.jpg";
  
  var img = Image.FromFile(image_path);
  
  Rectangle crop = new Rectangle(x, y, width, height);
  
  Bitmap bmp = new Bitmap(crop.Width, crop.Height);
  using (var gr = Graphics.FromImage(bmp))
  {
      gr.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);
  }
  
  
  if (System.IO.File.Exists(image_path))
  {
      System.IO.File.Delete(image_path);
  }
  
  bmp.Save(image_path, ImageFormat.Jpeg);
  }
  </code></pre>
  
  <p><strong>This gives an error like:</strong></p>
  
  <blockquote>
    <p>An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code</p>
    
    <p>Additional information: The process cannot access the file
    'C:\Users\Admin\Desktop\test.jpg' because it is being used by another
    process.</p>
  </blockquote>
  
  <p>When I add <code>img.Dispose()</code> I don't get the above error and I'm able to save it.But it saves the blank image with the given width and height.</p>
  
  <p>Can anyone help me out with this??</p>