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.
It looks fine in the html view, but when it published to PDF, the image comes out smaller than what is expected.
Here is the cropping code I am using:
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;
}
I have also tried this:
Bitmap temp = (Bitmap)System.Drawing.Image.FromFile(img);
Bitmap bmap = (Bitmap)temp.Clone();
if (xPosition + width > temp.Width)
width = temp.Width - xPosition;
if (yPosition + height > temp.Height)
height = temp.Height - yPosition;
Rectangle rect = new Rectangle(xPosition, yPosition, width, height);
temp = (Bitmap)bmap.Clone(rect, bmap.PixelFormat);
I am writing this out to the context stream:
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();
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.