尝试调整大小和压缩高度,只保持高宽比与良好的质量

本文关键字:高宽比 调整 高度 压缩 | 更新日期: 2023-09-27 18:15:14

这里我正在处理图像从文件加载它覆盖目标图像,将小写名称转换为大写名称但是这里它使用固定大小来调整大小,我需要将高度调整为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;
    }
    //--------------------------------------------------------------------------------//

尝试调整大小和压缩高度,只保持高宽比与良好的质量

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

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

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

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

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

注意,调整大小算法的质量与保存时文件压缩的质量是不一样的。这两种操作都是有损的。我建议您使用最佳质量算法调整大小(更新到上面所示),然后尝试保存质量,直到找到一个有效的。