试图调整高度和压缩高度只保持高宽比和高质量

时间:2014-07-28 07:01:37

标签: c# image

这里我正在处理从文件加载它的图像 并覆盖目标图像,将小写名称转换为大写 但是这里使用固定大小调整大小,我需要调整高度为260像素,并保持其宽高比不设置图像宽度

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

    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;
    }
    //--------------------------------------------------------------------------------//

1 个答案:

答案 0 :(得分:0)

你的意思是你只想将图像调整到指定的高度,保持宽度成比例?

    /// <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;
    }

注意 - 不要显式处理Graphics g,而是使用using语句,因为这可以保证在发生异常时进行处理。

更新我建议在调用方法内的ResizedBitmap语句中包装using

更新2 我找不到保存指定最大尺寸的JPG的方法。您可以做的是以指定的质量保存它,如果文件太大,请再次尝试使用较低的质量:

    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;
    }

请注意,调整大小算法的质量与保存时文件压缩的​​质量不同。这两项操作都是lossy。我建议您使用最优质的算法调整大小(更新为上面显示),然后尝试保存质量,直到找到有效的算法。