title: Crop image using a fixed-size draggable picturebox
body: <p>I'm working on a winforms project that involves cropping an image. My goal is to do this by using a fixed-size draggable picturebox control, allowing the user to select the area they want to preserve.</p>
  
  <p>My problem is when I crop the image; it <em>"works"</em>, but the crop area offsets a little. Here's the result I get:</p>
  
  <p><img src="https://i.stack.imgur.com/paWhn.png" alt="Original image">
  <img src="https://i.stack.imgur.com/8QY5x.png" alt="Cropped image"></p>
  
  <p>To clarify, I'm not talking about the zooming, that's per design. Notice the orange box is mostly focusing on the eye of the storm, but the cropped image is not.</p>
  
  <p>This is my code for the crop operation:</p>
  
  <pre class="lang-cs prettyprint-override"><code>private void tsbRecortar_Click(object sender, EventArgs e)
  {
      Rectangle recorte = new Rectangle(pbxSeleccion.Location.X, pbxSeleccion.Location.Y, pbxSeleccion.Width, pbxSeleccion.Height);
  
      foto = recortarImagen(foto, recorte);
      pbxImagen.Image = foto;
  }
  
  private Image recortarImagen(Image imagen, Rectangle recuadro)
  {
      try
      {
          Bitmap bitmap = new Bitmap(imagen);
          Bitmap cropedBitmap = bitmap.Clone(recuadro, bitmap.PixelFormat);
  
          return (Image)(cropedBitmap);
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message, "Error");
  
          return null;
      }
  }
  </code></pre>
  
  <p><strong><em>pbxSeleccion</em></strong> is the draggable orange rectangle; its parent is <strong><em>pbxImage</em></strong> (I re-parent it on form's load).</p>
  
  <p>As you can see, I'm using the coordinates of <em>pbxSeleccion</em> to define the starting point of the crop area, but is not working as expected... sometimes, I even get an "Out of Memory" exception.</p>
  
  <p>I think this has to do with how the image loads in the parent picturebox, something about how the margin is handled "under the hood", but nothing I tried fixes it... just changes the magnitude of the offset.</p>
  
  <p>Searching the web and SO has helped me a lot, but for this particular issue, I can't seem to find an answer... please, feel free to point out improvements to my code, I haven't been coding for long and I'm new to C# and .NET</p>
  
  <p>Any help is highly appreciated. Cheers!</p>