Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Image Resizing - Losing EXIF

Yes yes... I've seen other posts related to this issue, and yes... I've googled about it.

But so far, I was not able to get to the result I need.

I'm loading a large image taken in 300 dpi, and I need to resize it.

I know... I know... dpi is relative and doesn't really matter... what matters are the dimensions in pixels:

DPI is essentially the number of pixels that correspond to an inch when the image is printed not when it is viewed on a screen. Therefore by increasing the DPI of the image, you do not increase the size of the image on the screen. You only increase the quality of print.

Even though the DPI information stored in the EXIF of an image is somewhat useless, it is causing me problems.

The image I'm resizing is losing the original exif information, including the horizontal and vertical resolution (dpi), and thus it is saving with a default of 96 dpi. Possible reason to this is that only JPEG and another format can hold metadata information.

The end image result is should look like this: 275x375 at 300dpi Instead is looking like this: 275x375 at 96dpi

You can argue that they are they same, and I agree, but we have a corel draw script that used to load these images, and since this dpi information is different, it places it in different sizes on the document.

Here's what I'm using for resizing:

public System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
    {
        Bitmap result = new Bitmap(width, height);

        // set the resolutions the same to avoid cropping due to resolution differences
        result.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        //use a graphics object to draw the resized image into the bitmap
        using (Graphics graphics = Graphics.FromImage(result))
        {
            //set the resize quality modes to high quality
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //draw the image into the target bitmap
            graphics.DrawImage(image, 0, 0, result.Width, result.Height);
        }

        //return the resulting bitmap
        return result;
    }

That does the work very well, but loses the EXIF information.

Setting the SetResolution to SetResolution(300, 300) does not work!

I looked at reading and changing the EXIF information of an image, and I've tried:

public void setImageDpi(string Filename, string NewRes)
    {
        Image Pic;
        PropertyItem[] PropertyItems;
        byte[] bDescription = new Byte[NewRes.Length];
        int i;
        string FilenameTemp;
        System.Drawing.Imaging.Encoder Enc = System.Drawing.Imaging.Encoder.Transformation;
        EncoderParameters EncParms = new EncoderParameters(1);
        EncoderParameter EncParm;
        ImageCodecInfo CodecInfo = GetEncoderInfo("image/jpeg");

        // copy description into byte array
        for (i = 0; i < NewRes.Length; i++) bDescription[i] = (byte)NewRes[i];

        // load the image to change
        Pic = Image.FromFile(Filename);

        foreach (PropertyItem item in Pic.PropertyItems)
        {
            if (item.Id == 282 || item.Id == 283)
            {
                PropertyItem myProperty = item;
                myProperty.Value = bDescription;
                myProperty.Type = 2;
                myProperty.Len = NewRes.Length;
                Pic.SetPropertyItem(item);
                Console.WriteLine(item.Type);
            }
        }

        // we cannot store in the same image, so use a temporary image instead
        FilenameTemp = Filename + ".temp";

        // for lossless rewriting must rotate the image by 90 degrees!
        EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate90);
        EncParms.Param[0] = EncParm;

        // now write the rotated image with new description
        Pic.Save(FilenameTemp, CodecInfo, EncParms);

        // for computers with low memory and large pictures: release memory now
        Pic.Dispose();
        Pic = null;
        GC.Collect();

        // delete the original file, will be replaced later
        System.IO.File.Delete(Filename);

        // now must rotate back the written picture
        Pic = Image.FromFile(FilenameTemp);
        EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate270);
        EncParms.Param[0] = EncParm;
        Pic.Save(Filename, CodecInfo, EncParms);

        // release memory now
        Pic.Dispose();
        Pic = null;
        GC.Collect();

        // delete the temporary picture
        System.IO.File.Delete(FilenameTemp);
    }

That didn't work either.

I tried looking and changing the EXIF information for DPI (282 and 283) later in the process as such:

        Encoding _Encoding = Encoding.UTF8;
        Image theImage = Image.FromFile("somepath");

        PropertyItem propItem282 = theImage.GetPropertyItem(282);
        propItem282.Value = _Encoding.GetBytes("300" + '\0');
        theImage.SetPropertyItem(propItem282);

        PropertyItem propItem283 = theImage.GetPropertyItem(283);
        propItem283.Value = _Encoding.GetBytes("300" + '\0');
        theImage.SetPropertyItem(propItem283);

        theImage.Save("somepath");

But the program crashes saying that Property Cannot be Found.

If the property doesn't exist, apparently I can't add it:

A PropertyItem is not intended to be used as a stand-alone object. A PropertyItem object is intended to be used by classes that are derived from Image. A PropertyItem object is used to retrieve and to change the metadata of existing image files, not to create the metadata. Therefore, the PropertyItem class does not have a defined Public constructor, and you cannot create an instance of a PropertyItem object.

I'm stuck... all I need is a resized image with a dpi set to 300, it shouldn't be so hard.

Any help much appreciated. Thanks

like image 438
Naner Avatar asked Jul 23 '13 15:07

Naner


1 Answers

The following code worked for me:

const string InputFileName = "test_input.jpg";
const string OutputFileName = "test_output.jpg";
var newSize = new Size(640, 480);

using (var bmpInput = Image.FromFile(InputFileName))
{
    using (var bmpOutput = new Bitmap(bmpInput, newSize))
    {
        foreach (var id in bmpInput.PropertyIdList)
            bmpOutput.SetPropertyItem(bmpInput.GetPropertyItem(id));
        bmpOutput.SetResolution(300.0f, 300.0f);
        bmpOutput.Save(OutputFileName, ImageFormat.Jpeg);
    }
}

When I inspect the output file I can see EXIF data and the DPI has been changed to 300.

like image 178
RogerN Avatar answered Oct 04 '22 23:10

RogerN