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

本文介绍了一种通过C#实现的图片缩略图生成方法,包括如何定义缩略图的最大尺寸,以及如何按比例调整原始图片大小以适应指定尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/vaevvaev/p/6885255.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值