C#实现缩放和剪裁图片的方法示例

92 篇文章 5 订阅
51 篇文章 6 订阅

C#实现缩放和剪裁图片的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Project
{
  class ImageOperation
  {
    /// <summary>
    /// Resize图片
    /// </summary>
    /// <param name="bmp">原始Bitmap </param>
    /// <param name="newW">新的宽度</param>
    /// <param name="newH">新的高度</param>
    /// <param name="Mode">保留着,暂时未用</param>
    /// <returns>处理以后的图片</returns>
    public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH, int Mode)
    {
      try
      {
        Bitmap b = new Bitmap(newW, newH);
        Graphics g = Graphics.FromImage(b);
        // 插值算法的质量
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
        g.Dispose();
        return b;
      }
      catch
      {
        return null;
      }
    }
    /// <summary>
    /// 剪裁 -- 用GDI+
    /// </summary>
    /// <param name="b">原始Bitmap</param>
    /// <param name="StartX">开始坐标X</param>
    /// <param name="StartY">开始坐标Y</param>
    /// <param name="iWidth">宽度</param>
    /// <param name="iHeight">高度</param>
    /// <returns>剪裁后的Bitmap</returns>
    public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
    {
      if (b == null)
      {
        return null;
      }
      int w = b.Width;
      int h = b.Height;
      if (StartX >= w || StartY >= h)
      {
        return null;
      }
      if (StartX + iWidth > w)
      {
        iWidth = w - StartX;
      }
      if (StartY + iHeight > h)
      {
        iHeight = h - StartY;
      }
      try
      {
        Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmpOut);
        g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
        g.Dispose();
        return bmpOut;
      }
      catch
      {
        return null;
      }
    }
  }
}

目标其实都是new Rectangle(0, 0, iWidth, iHeight),缩放算法把整个原始图都往目标区域里塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始区域上等宽等高的那个区域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目标区域里。




public  static  Bitmap GetThumbnail(Bitmap b, int  destHeight, int  destWidth)  
         {          
             System.Drawing.Image imgSource = b;     
             System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat; 
             int  sW = 0, sH = 0;         
             // 按比例缩放          
             int  sWidth = imgSource.Width;
             int  sHeight = imgSource.Height;
             if  (sHeight > destHeight || sWidth > destWidth)
             {              
                 if  ((sWidth * destHeight) > (sHeight * destWidth))   
                 {                
                     sW = destWidth;   
                     sH = (destWidth * sHeight) / sWidth; 
                 }              
                 else           
                 {          
                     sH = destHeight;   
                     sW = (sWidth * destHeight) / sHeight;   
                 }          
             }          
             else        
             {         
                 sW = sWidth; 
                 sH = sHeight; 
             }   
             Bitmap outBmp = new  Bitmap(destWidth, destHeight); 
             Graphics g = Graphics.FromImage(outBmp);     
             g.Clear(Color.Transparent);        
             // 设置画布的描绘质量        
             g.CompositingQuality = CompositingQuality.HighQuality;
             g.SmoothingMode = SmoothingMode.HighQuality;      
             g.InterpolationMode = InterpolationMode.HighQualityBicubic;   
             g.DrawImage(imgSource, new  Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);    
             g.Dispose();     
             // 以下代码为保存图片时,设置压缩质量    
             EncoderParameters encoderParams = new  EncoderParameters(); 
             long [] quality = new  long [1];     
             quality[0] = 100;     
             EncoderParameter encoderParam = new  EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);  
             encoderParams.Param[0] = encoderParam;  
             imgSource.Dispose();        
             return  outBmp;     
         }



实例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace CompressImageTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Image SourceImage = null;
        
        private void button_SelectImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            string filePath = "";
            if(openFileDialog.ShowDialog()==DialogResult.OK)
            {


                filePath = openFileDialog.FileName;


            }
             SourceImage=Image.FromFile(filePath);
            this.textBox_CurrentWidth.Text = Convert.ToString(SourceImage.Width);
            this.textBox_CurrentHeight.Text = Convert.ToString(SourceImage.Height);
            this.textBox_SetWidth.Text = "";
            this.textBox_SetHeight.Text = "";
            this.pictureBox1.Image = SourceImage;
            SaveImageToStream(SourceImage);//保存图像
           
        }
        public  Bitmap GetThumbnail(Bitmap b,  int destWidth, int destHeight)
        {
            System.Drawing.Image imgSource = b;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // 按比例缩放           
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;
            if (sHeight > destHeight || sWidth > destWidth)
            {
                if ((sWidth * destHeight) > (sHeight * destWidth))
                {
                    sW = destWidth;
                    sH = (destWidth * sHeight) / sWidth;
                }
                else
                {
                    sH = destHeight;
                    sW = (sWidth * destHeight) / sHeight;
                }
            }
            else
            {
                sW = sWidth;
                sH = sHeight;
            }
            Bitmap outBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.Transparent);
            // 设置画布的描绘质量         
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            // 以下代码为保存图片时,设置压缩质量     
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            imgSource.Dispose();
            return outBmp;
        }


        private void compress_Click(object sender, EventArgs e)
        {
            SourceImage=SaveImage = GetImageFromStream(Ms);//获取图像
            Bitmap bitmap = new Bitmap(SourceImage);
            SourceImage=  GetThumbnail(bitmap, Convert.ToInt32(textBox_SetWidth.Text), Convert.ToInt32(textBox_SetHeight.Text));
            //SourceImage=ResizeImage(bitmap, Convert.ToInt32(textBox_SetWidth.Text), Convert.ToInt32(textBox_SetHeight.Text), 0);
            pictureBox1.Image = SourceImage;
            pictureBox1.i
          this.textBox_CurrentWidth.Text = Convert.ToString(SourceImage.Width);
          this.textBox_CurrentHeight.Text = Convert.ToString(SourceImage.Height);
        }


        public  Bitmap ResizeImage(Bitmap bmp, int newW, int newH, int Mode)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch
            {
                return null;
            }
        }




        public static Image SaveImage;//保存图像
        public static MemoryStream Ms;
        public static void SaveImageToStream(Image image)//保存图像
        {


            Ms = new MemoryStream();
            image.Save(Ms, System.Drawing.Imaging.ImageFormat.Png);


        }
        public static Image GetImageFromStream(Stream stream)//获取图像
        {


            MemoryStream ms = stream as MemoryStream;
            ms.Position = 0;
            Image image = Image.FromStream(ms);
            return image;
            //ms.Close();


        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值