按大小缩放图片
2016-01-17 21:18
429 查看
这是一段c#代码,根据指定长宽把图片按原比例进行缩放,产生的空白部分可指定颜色。
public static Bitmap ShrinkImage(Bitmap img, int width, int height, Color bgColor) { Bitmap ret = null; if (img.Width == 0 || img.Height == 0) { ret = new Bitmap(0, 0); return ret; } // calc the smaller ratio double w = (double)width / img.Width; double h = (double)height / img.Height; double r = w > h ? h : w; ret = new Bitmap(width, height); Bitmap img2 = null; if (w > 1.0 && h > 1.0) { // pic smaller than rect img2 = img; } else { // one side is bigger that rect img2 = new Bitmap(img.GetThumbnailImage((int)(img.Width*r), (int)(img.Height*r), null, new IntPtr())); } int x = (width - img2.Width) / 2; int y = (height - img2.Height) / 2; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { if ((i >= x && i < (img2.Width+x)) && (j >= y && j < (img2.Height+y))) { ret.SetPixel(i, j, img2.GetPixel(i - x, j - y)); } else { ret.SetPixel(i, j, bgColor); } } } return ret; }
相关文章推荐
- c#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#比较二个数组并找出相同或不同元素的方法
- C#生成饼形图及添加文字说明实例代码
- C#判等对象是否相等的方法汇总
- C#简单的向量用法实例教程