C# – Save Image Preserving Resolution in C#


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:

            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

            return bmp;
        catch (Exception ex)
            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);

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.

Best Solution

When using a PDF you have to bear in mind that you are looking at the print resolution rather than the screen resolution.

A 600 x 600 pixel image will occupy approximately half the width of the screen on a 1280 x 1024 resolution monitor.

However if the print output is 200 dpi it will occupy 3 inches, but if it's set to 300 dpi it will only occupy 2 inches.

I don't know enough about the PDF format to say what you need to do to get this to work, but my guess is that you need to work back from the physical size on the paper via the dpi of the output to get the size in pixels of the image:

pixel width = physical width * dpi
Related Question