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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM