• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#图片按比例缩放

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

工具类代码:

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中的where泛型约束发布时间:2022-07-14
下一篇:
CommMonitor8.0串口过滤驱动SDKDLL版本C#/Delphi调用DEMO发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap