title: Save Image Preserving Resolution in C#
body: <p>I am trying to crop an image. I have found multiple ways to do this, however none are performing how I would like. Once the image is cropped, I am sending it to a PDF generator. If I send the normal jpg, it works fine, however if I crop the image, it does not come through to the PDF in the correct size. I think it might be to do with resolution.</p>
  
  <p>It looks fine in the html view, but when it published to PDF, the image comes out smaller than what is expected.</p>
  
  <p>Here is the cropping code I am using:</p>
  
  <pre><code>            try
          {
              System.Drawing.Image image = System.Drawing.Image.FromFile(img);
              Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
              bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
  
              Graphics gfx = Graphics.FromImage(bmp);
              gfx.SmoothingMode = SmoothingMode.AntiAlias;
              gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
              gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
              gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
              // Dispose to free up resources
              image.Dispose();
              //bmp.Dispose();
              gfx.Dispose();
  
              return bmp;
          }
          catch (Exception ex)
          {
              //MessageBox.Show(ex.Message);
              return null;
          }
  </code></pre>
  
  <p>I have also tried this:</p>
  
  <pre><code>Bitmap temp = (Bitmap)System.Drawing.Image.FromFile(img);
          Bitmap bmap = (Bitmap)temp.Clone();
          if (xPosition + width &gt; temp.Width)
              width = temp.Width - xPosition;
          if (yPosition + height &gt; temp.Height)
              height = temp.Height - yPosition;
          Rectangle rect = new Rectangle(xPosition, yPosition, width, height);
          temp = (Bitmap)bmap.Clone(rect, bmap.PixelFormat);
  </code></pre>
  
  <p>I am writing this out to the context stream:</p>
  
  <pre><code>Bitmap bm = Helper.CropImage(@"MyFileLocation", 0, 0, 300, 223);
          context.Response.ContentType = "image/jpg";
          bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
          bm.Dispose();
  </code></pre>
  
  <p>Interestingly, when I try a tiff image, and change the context type, I am receiving a generic GDI+ error. From research, this looks like a seek issue, but not sure how to resolve it either.</p>