net2.0 生成缩略图,与指定比例

本文介绍了一种基于C#的图片缩放处理方法,通过指定宽度和高度来生成缩略图,并保持图片的纵横比不变。该方法适用于需要对图片进行预处理的应用场景。

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

  1. //int_Height int_Width 指定高度和指定宽度 input_Imgfile,out_ImgFile为原图片和缩小后图片的路径。
  2. public static void Thumbnail (int int_Width, int int_Height, string input_ImgFile, string out_ImgFile)
  3. {
  4. System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgFile);
  5. float New_Width; // 新的宽度
  6. float New_Height; // 新的高度
  7. float Old_Width,Old_Height; //原始高宽
  8. int flat = 0;//标记图片是不是等比
  9. int xPoint = 0;//若果要补白边的话,原图像所在的x,y坐标。
  10. int yPoint=0;
  11. //判断图片
  12. Old_Width = (float)oldimage.Width;
  13. Old_Height = (float)oldimage.Height;
  14. if ((Old_Width / Old_Height) > ((float)int_Width / (float)int_Height)) //当图片太宽的时候
  15. {
  16. New_Height = Old_Height * ((float)int_Width / (float)Old_Width);
  17. New_Width = (float)int_Width;
  18. //此时x坐标不用修改
  19. yPoint = (int)(((float)int_Height - New_Height) / 2);
  20. flat = 1;
  21. }
  22. else if ((oldimage.Width / oldimage.Height) == ((float)int_Width / (float)int_Height))
  23. {
  24. New_Width = int_Width;
  25. New_Height = int_Height;
  26. }
  27. else
  28. {
  29. New_Width = (int)oldimage.Width * ((float)int_Height / (float)oldimage.Height); //太高的时候
  30. New_Height = int_Height;
  31. //此时y坐标不用修改
  32. xPoint = (int)(((float)int_Width - New_Width) / 2);
  33. flat = 1;
  34. }
  35. // ===缩小图片===
  36. System.Drawing.Image thumbnailImage = oldimage.GetThumbnailImage((int)New_Width, (int)New_Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
  37. Bitmap bm = new Bitmap(thumbnailImage);
  38. if (flat != 0)
  39. {
  40. Bitmap bmOutput = new Bitmap(int_Width,int_Height);
  41. Graphics gc = Graphics.FromImage(bmOutput);
  42. SolidBrush tbBg = new SolidBrush(Color.White);
  43. gc.FillRectangle(tbBg,0, 0, int_Width, int_Height); //填充为白色
  44. gc.DrawImage(bm,xPoint, yPoint, (int)New_Width, (int)New_Height);
  45. bmOutput.Save(out_ImgFile);
  46. }
  47. else
  48. {
  49. bm.Save(out_ImgFile);
  50. }
  51. }
[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/631872/viewspace-1050389/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/631872/viewspace-1050389/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值