none
GDI+ / How to save G4 TIFF to PNG and maintain DPI of original TIF? RRS feed

  • Question

  • I have G4 TIFFs that I wish to convert to png for purposes of sending to web browser client.  The .NET GDI+ code seems to save the G4 as a PNG but the DPI between the original TIF and the newly created DPI are different.   In the original TIF, the DPI is 200 x 200 but in the new PNG the DPI is 96 x 96.  How do you preserve the DPI of the original TIF when converting/saving to PNG?

     private void savePng(string path, Bitmap img, long quality)
            {
                // Encoder parameter for image quality
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                EncoderParameter colorDepthParam = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8);

                // Jpeg image codec
                ImageCodecInfo pngCodec = this.getEncoderInfo("image/png");

                if (pngCodec == null)
                    return;
                
                EncoderParameters encoderParams = new EncoderParameters(2);
                encoderParams.Param[0] = qualityParam;
                encoderParams.Param[1] = colorDepthParam;

                img.Save(path, pngCodec, encoderParams);

                colorDepthParam.Dispose();
                qualityParam.Dispose();
                encoderParams.Dispose();
            }

            private ImageCodecInfo getEncoderInfo(string mimeType)
            {
                // Get image codecs for all image formats
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

                // Find the correct image codec
                for (int i = 0; i < codecs.Length; i++)
                    if (codecs[i].MimeType == mimeType)
                        return codecs[i];

                return null;
            }

    Wednesday, July 18, 2012 7:43 PM

Answers

  • The DPI isn't important, set it to whatever you wish.  It's a guide to the resolution of the original device that recorded the image.  As long as your png has the same total pixels as the tiff, you've lost no information.
    • Edited by JohnWein Wednesday, July 18, 2012 11:10 PM
    • Marked as answer by scott_m Thursday, July 19, 2012 1:35 AM
    Wednesday, July 18, 2012 11:09 PM