上传图片时等比缩放的一个小小算法

protected void Button1_Click(object sender, EventArgs e)
       {
           int width = 300, height = 300;//生成缩略图时定义一个最大的宽和高
           System.Drawing.Image img = System.Drawing.Image.FromFile("d:/test.jpg");
           int swidth =img.Width;//源图片的宽
           int sheight = img.Height;//源图片的高
           var info = new SImg
           {
               width = swidth,
               height = sheight
           };
           info.GetHW(width, height, info);
           //得到缩放后的宽和高
           int w = info.width;
           int h = info.height;
           //获取缩略图
           System.Drawing.Image smallimg = img.GetThumbnailImage(w, h, new System.Drawing.Image.GetThumbnailImageAbort(() => { return false; }), IntPtr.Zero);
   }
public class SImg { public int width { get; set; } public int height { get; set; } public void GetHW(int width, int height, SImg img) { //如果宽和高任意一个超过定义的宽和高 执行等比 if (img.width > width || img.height > height) { img.width = img.width / 2; img.height = img.height / 2; GetHW(width, height, img); } } }

Image.GetThumbnailImage 方法

public Image GetThumbnailImage (
	int thumbWidth,
	int thumbHeight,
	GetThumbnailImageAbort callback,
	IntPtr callbackData
)

参数

thumbWidth

请求的缩略图的宽度(以像素为单位)。

thumbHeight

请求的缩略图的高度(以像素为单位)。

callback

一个 Image.GetThumbnailImageAbort 委托。在 GDI+ 1.0 版中不使用此委托。即便如此,也必须创建一个委托并在该参数中传递对此委托的引用。

callbackData

必须为 Zero

posted @ 2017-05-21 16:41  君莫笑·秋  阅读(1589)  评论(0编辑  收藏  举报