-1

here i am processing the image loading it from file and overwriting the destination image converting the lowercase name to uppercase but here its resizing using a fixed size, i need to resize with height 260 pixels and maintaining its aspect ratio not setting the image width

//--------------------------------------------------------------------------------//

    private void ProcessImage()
    {
        if (File.Exists(pictureBox1.ImageLocation))
        {
            string SourceImagePath = pictureBox1.ImageLocation;
            string ImageName = Path.GetFileName(SourceImagePath).ToUpper();
            string TargetImagePath = Properties.Settings.Default.ImageTargetDirectory + "\\" + ImageName;
           //Set the image to uppercase and save as uppercase
            if (SourceImagePath.ToUpper() != TargetImagePath.ToUpper())
            {

                using (Image Temp = Image.FromFile(SourceImagePath))
                {
                  // my problem is here, i need to resize only by height
                  // and maintain aspect ratio
                    Bitmap ResizedBitmap = resizeImage(Temp, new Size(175, 260));

                    //ResizedBitmap.Save(@TargetImagePath);
                    ResizedBitmap.Save(@TargetImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                }
                pictureBox1.ImageLocation = @TargetImagePath;
                File.Delete(SourceImagePath);
            }
        }
    }
    //--------------------------------------------------------------------------------//
    private static Bitmap resizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return b;
    }
    //--------------------------------------------------------------------------------//
  • Does this article help? I found the library easy to use: http://www.hanselman.com/blog/NuGetPackageOfTheWeekImageProcessorLightweightImageManipulationInC.aspx – Christian Sauer Jul 28 '14 at 07:08

1 Answers1

0

You mean you just want to resize the image to a specified height, keeping the width proportionate?

    /// <summary>
    /// Resize the image to have the selected height, keeping the width proportionate.
    /// </summary>
    /// <param name="imgToResize"></param>
    /// <param name="newHeight"></param>
    /// <returns></returns>
    private static Bitmap resizeImage(Image imgToResize, int newHeight)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height; 

        float nPercentH = ((float)newHeight / (float)sourceHeight);

        int destWidth = Math.Max((int)Math.Round(sourceWidth * nPercentH), 1); // Just in case;
        int destHeight = newHeight;

        Bitmap b = new Bitmap(destWidth, destHeight);
        using (Graphics g = Graphics.FromImage((Image)b))
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        }

        return b;
    }

Note - rather than explicitly disposing the Graphics g, use the using statement, since that guarantees disposal in the event of an exception.

Update I suggest wrapping ResizedBitmap in a using statement also, inside the calling method.

Update 2 I cannot find a way for you to save a JPG with a specified maximum size. What you can do is save it with a specified quality, and if the file is too large, try again with a lower quality:

    public static void SaveJpegWithSpecifiedQuality(this Image image, string filename, int quality)
    {
        // http://msdn.microsoft.com/en-us/library/ms533844%28v=vs.85%29.aspx
        // A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.
        if (quality < 0 || quality > 100)
        {
            throw new ArgumentOutOfRangeException("quality");
        }

        System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
        EncoderParameters encoderParams = new EncoderParameters(1);
        EncoderParameter encoderParam = new EncoderParameter(qualityEncoder, (long)quality);
        encoderParams.Param[0] = encoderParam;

        image.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParams);
    }

    private static ImageCodecInfo GetEncoder(ImageFormat format)
    {
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }
        return null;
    }

Note that the quality of the resizing algorithm is not the same thing as the quality of the file compression in saving. Both operations are lossy. I recommend you resize with the best quality algorithm (updated to show above) and then experiment with save qualities until you find one that works.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • You mean you just want to resize the image to a specified height, keeping the width proportionate? Yes that is correct – CoDeBreaKeR Jul 28 '14 at 07:26
  • the ResizeImage code works well. but the above ProcessImage () code how should i have it resized maintaining a quality of 70 and height 260 keeping aspect ratio ? – CoDeBreaKeR Jul 28 '14 at 07:41
  • @Garrick Oduber - "quality of 70" - please define this term. [This answer](http://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality/87786#87786) has suggestions for the highest quality resizing algorithms available in the default c# libraries. – dbc Jul 28 '14 at 07:45
  • For example if i resize in photoshop i choose quality High which saves it in a good quality and the size of the file is small enough . maybe if i can have an option in code to try different quality i can test till i get the quality i need. , i am trying to resize a movie cover to a 30 /40kb size. but the max height must be 260 – CoDeBreaKeR Jul 28 '14 at 07:48