C#图片按比例缩放

Posted 秋荷雨翔的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#图片按比例缩放相关的知识,希望对你有一定的参考价值。

工具类代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZoomImage.Utils
{
    /// <summary>
    /// 图片缩放
    /// </summary>
    public class ZoomImageUtil
    {
        #region 图片缩放
        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="bArr">图片字节流</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        public static byte[] GetThumbnail(byte[] bArr, int width, int height)
        {
            if (bArr == null) return null;
            MemoryStream ms = new MemoryStream(bArr);
            Bitmap bmp = (Bitmap)Image.FromStream(ms);
            ms.Close();

            bmp = GetThumbnail(bmp, width, height);

            ImageCodecInfo imageCodecInfo = GetEncoder(ImageFormat.Jpeg);
            EncoderParameters encoderParameters = new EncoderParameters(1);
            EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
            encoderParameters.Param[0] = encoderParameter;

            ms = new MemoryStream();
            bmp.Save(ms, imageCodecInfo, encoderParameters);
            byte[] result = ms.ToArray();
            ms.Close();
            bmp.Dispose();

            return result;
        }
        #endregion

        #region 图片缩放
        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        private static Bitmap GetThumbnail(Bitmap bmp, int width, int height)
        {
            if (width == 0 && height == 0)
            {
                width = bmp.Width;
                height = bmp.Height;
            }
            else
            {
                if (width == 0)
                {
                    width = height * bmp.Width / bmp.Height;
                }
                if (height == 0)
                {
                    height = width * bmp.Height / bmp.Width;
                }
            }

            Image imgSource = bmp;
            Bitmap outBmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.Transparent);
            // 设置画布的描绘质量     
            g.CompositingQuality = CompositingQuality.Default;
            g.SmoothingMode = SmoothingMode.Default;
            g.InterpolationMode = InterpolationMode.Default;
            g.DrawImage(imgSource, new Rectangle(0, 0, width, height + 1), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            imgSource.Dispose();
            bmp.Dispose();
            return outBmp;
        }
        #endregion

        #region 椭圆形缩放
        /// <summary>
        /// 椭圆形缩放
        /// </summary>
        /// <param name="bArr">图片字节流</param>
        /// <param name="width">目标宽度,若为0,表示宽度按比例缩放</param>
        /// <param name="height">目标长度,若为0,表示长度按比例缩放</param>
        public static byte[] GetEllipseThumbnail(byte[] bArr, int width, int height)
        {
            if (bArr == null) return null;
            MemoryStream ms = new MemoryStream(bArr);
            Bitmap bmp = (Bitmap)Image.FromStream(ms);

            Bitmap newBmp = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(newBmp))
            {
                using (TextureBrush br = new TextureBrush(bmp))
                {
                    br.ScaleTransform(width / (float)bmp.Width, height / (float)bmp.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, new Size(width, height)));
                }
            }
            MemoryStream newMs = new MemoryStream();
            newBmp.Save(newMs, System.Drawing.Imaging.ImageFormat.Png);
            byte[] result = newMs.ToArray();

            bmp.Dispose();
            newBmp.Dispose();
            ms.Close();
            newMs.Dispose();

            return result;
        }
        #endregion

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

    }
}
View Code

使用示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZoomImage.Utils;

namespace ZoomImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = true;
        }

        private void txtWidth_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtHeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void btnSelectImage_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtWidth.Text == "" && txtHeight.Text == "")
                {
                    MessageBox.Show("请输入宽度或高度!");
                    return;
                }

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            string path = Path.GetDirectoryName(openFileDialog1.FileNames[0]) + "\\\\NewImage\\\\";
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            foreach (string file in Directory.GetFiles(path))
                            {
                                File.Delete(file);
                            }

                            int i = 0;
                            foreach (string fileName in openFileDialog1.FileNames)
                            {
                                Bitmap bmp = ZoomImageUtil.GetThumbnail(new Bitmap(fileName), Convert.ToInt32(txtWidth.Text == "" ? "0" : txtWidth.Text), Convert.ToInt32(txtHeight.Text == "" ? "0" : txtHeight.Text));

                                this.Invoke(new InvokeDelegate(() =>
                                {
                                    if (cbxExt.SelectedItem == null)
                                    {
                                        bmp.Save(path + Path.GetFileName(fileName));
                                    }
                                    else
                                    {
                                        bmp.Save(path + Path.GetFileNameWithoutExtension(fileName) + (string)cbxExt.SelectedItem);
                                    }
                                }));
                                this.Invoke(new InvokeDelegate(() =>
                                {
                                    lblProgress.Text = string.Format("进度:{1}/{0}", openFileDialog1.FileNames.Length, ++i);
                                }));
                                Thread.Sleep(1);
                            }

                            MessageBox.Show("成功!");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }

    /// <summary>
    /// 跨线程访问控件的委托
    /// </summary>
    public delegate void InvokeDelegate();
}
View Code

 

以上是关于C#图片按比例缩放的主要内容,如果未能解决你的问题,请参考以下文章

html中怎么把图片按比例缩放在<span>里面

Qt 图片适应QLabel控件大小(饱满缩放和按比例缩放)

在C#中,在ImageList中,如何按比例显示缩略图

如何按比例缩放UIImageView

图片居中按比例显示鼠标滚动缩放鼠标拖动平移

两张图片叠加成一张图&&按XY轴比例缩放图片