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();

}
    }
}

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

  1. 如何使用python爬取百度图片_python实现爬取百度图片的方法示例

    本文实例讲述了python实现爬取百度图片的方法.分享给大家供大家参考,具体如下: import json import itertools import urllib import requests ...

  2. python爬去百度图片_python实现爬取百度图片的方法示例

    本文实例讲述了python实现爬取百度图片的方法.分享给大家供大家参考,具体如下: import json import itertools import urllib import requests ...

  3. python爬虫百度图片_python实现爬取百度图片的方法示例

    本文实例讲述了python实现爬取百度图片的方法.分享给大家供大家参考,具体如下: import json import itertools import urllib import requests ...

  4. python读取gif图片并显示_Python爬虫实现获取动态gif格式搞笑图片的方法示例

    本文实例讲述了python爬虫实现获取动态gif格式搞笑图片的方法.分享给大家供大家参考,具体如下: 有时候看到一些喜欢的动图,如果一个个取保存挺麻烦,有的网站还不支持右键保存,因此使用python来 ...

  5. css鼠标点在文字上背景透明,CSS实现文字半透明显示在图片上方法(示例代码)

    CSS实现文字半透明显示在图片上方法 在css中文字半透明我们会需要使用滤镜效果也就是css中的filter:alpha来实现了,下面来看两个文字显示在图片上并且半透明的例子. CSS让一行文字显示在 ...

  6. C#图片处理之:图片缩放和剪裁

    应听众点播要求,今天说说用C#做图片的缩放和剪裁,相信很多人会对这部分内容感兴趣,毕竟这个操作太实用了. 其实在GDI+中,缩放和剪裁可以看作同一个操作,无非就是原始区域的选择不同罢了.空口无凭,先看 ...

  7. html 图片整体缩放,html页面中css缩放图片的方法

    在html页面制作中,可以利用 CSS 中的 transform 属性对图片进行旋转,缩放,移动或倾斜的操作.而今天我们只说说 transform 属性对图片进行等比例的缩放操作. css trans ...

  8. css中图片缩放后不清晰解决方法

    场景:uniapp开发,头部滚动条图片模糊不清晰 示例: 在图片样式加上image-rendering属性 image-rendering: -webkit-optimize-contrast; im ...

  9. 【VUE】vue+vue-cropper实现上传剪裁图片

    一个优雅的图片裁剪插件vue-cropper,很方便新手入手 安装 npm install vue-cropper 使用 import VueCropper from vue-cropper impo ...

最新文章

  1. 使用Spring Boot和DJL进行深度学习
  2. mysql 内部安全性_MySQL数据库的内部以及外部安全性简介
  3. Oracle数据库时间戳转date类型进行判断操作
  4. letex编辑输出】pdf文件嵌入字体embedded fonts的问题
  5. eclipse安装插件速度很慢的解决方案
  6. OpenPose人体姿态估计详细配置(win10)
  7. 计算机团队霸气名称大全,最霸气最潮的团队名字
  8. 创业者最爱的美剧《硅谷》大结局竟然是这样!
  9. Predicting Semantic Map Representations from Images using Pyramid Occupancy Networks 翻译
  10. 模拟实现图片长按保存功能
  11. uAVS2 AVS2实时编码器
  12. 从国产浏览器更换到谷歌浏览器的心路历程
  13. 关于机器翻译,看这一篇就够了
  14. Maxent模型学习
  15. [echarts]echarts的canvas画布大小与容器大小不一致的解决方案
  16. DB2数据库的基础学习
  17. python的pandas库的pd.read_excel()常用解析
  18. 遭遇Win32.Loader.c,Trojan.PSW.Win32.GameOnline,Trojan.PSW.Win32.AskTao等2
  19. 图片表情制作,QQ斗图生成,搜狗图片搜索,自适应支持手机浏览
  20. 『cocos2d-x』diamond hunter宝石猎手

热门文章

  1. 计算机网络电信号误差,用0V~5V方式传输远方温度信号的弊端
  2. navicat导出数据到oracle,使用Navicat premium导出oracle数据库中数据到SQL server2008数据库中...
  3. jbl调音软件_[马自达] 佛山马自达昂克赛拉改装美国JBL汽车音响
  4. C和C++太难了。。搞这个方向进大厂它不香吗?
  5. 通俗易懂,嵌入式Linux驱动基础
  6. 基于FPGA多通道数据采集系统verilog设计
  7. linux系统下4k对齐,linux查看硬盘4K对齐方法
  8. html中刷新按钮的代码,常见的按钮类型 点击button刷新的几种常用代码
  9. java防止undo空间撑爆_秒杀系统设计补坑篇(seata回顾)
  10. 监控url_熬夜之作:一文带你了解Cat分布式监控