首页 > 代码库 > 批量修改图片的尺寸(c#)

批量修改图片的尺寸(c#)

项目需要,经常需要手动调整图片尺寸,流程太过麻烦,效率低下。所以写了一个小程序,以提高工作效率
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9. namespace ChangeImgSize
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. int num = 0;
  16. if (!System.IO.Directory.Exists("Img"))
  17. {
  18. System.IO.Directory.CreateDirectory("Img");
  19. Console.WriteLine("已创建Img目录,请把需要处理的图片放到该目录下");
  20. Console.ReadKey(true);
  21. return;
  22. }
  23. if (!System.IO.Directory.Exists("NewImg"))
  24. {
  25. System.IO.Directory.CreateDirectory("NewImg");
  26. }
  27. Console.WriteLine("请输入需要缩小的倍数");
  28. double size = Convert.ToDouble(Console.ReadLine());
  29. string[] fileStrs = System.IO.Directory.GetFiles("Img");
  30. foreach (string s in fileStrs)
  31. {
  32. System.IO.FileInfo info = new System.IO.FileInfo(s);
  33. if (info.Extension == ".png" || info.Extension == ".jpg")
  34. {
  35. Image img = GetFile(s);
  36. Bitmap bit = GetNewSizeBitmap(img,size);
  37. SaveImage(bit, info.Name, info.Extension);
  38. }
  39. ++num;
  40. }
  41. Console.WriteLine("共处理:" + num + "张图片,已经保存到NewImg目录中。");
  42. Console.ReadKey(true);
  43. }
  44. static public Image GetFile(string path)
  45. {
  46. FileStream stream = File.OpenRead(path);
  47. int fileLength = 0;
  48. fileLength = (int)stream.Length;
  49. Byte[] image = new Byte[fileLength];
  50. stream.Read(image, 0, fileLength);
  51. System.Drawing.Image result = System.Drawing.Image.FromStream(stream);
  52. stream.Close();
  53. return result;
  54. }
  55. static public Bitmap GetNewSizeBitmap(Image img , double size){
  56. int newWidth = Convert.ToInt32(img.Width / size);
  57. int newHeight = Convert.ToInt32(img.Height / size);
  58. Size s = new Size(newWidth, newHeight);
  59. Bitmap newBit = new Bitmap(img, s);
  60. return newBit;
  61. }
  62. static public void SaveImage(Bitmap bit,string name,string ext)
  63. {
  64. bit.Save(@"NewImg\" + name);
  65. bit.Dispose();
  66. Console.WriteLine("已处理:" + name);
  67. }
  68. }
  69. }



null


批量修改图片的尺寸(c#)