码迷,mamicode.com
首页 > 其他好文 > 详细

读取文件夹中所有的文件

时间:2017-03-07 23:02:11      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:ati   class   adk   size   byte   map   extension   pat   info   

  1. class Program
  2. {
  3. static double size = 2.443438914027149;
  4. static void Main(string[] args)
  5. {
  6. if (!System.IO.Directory.Exists("Img")){
  7. System.IO.Directory.CreateDirectory("Img");
  8. Console.WriteLine("已创建Img目录,请把需要处理的图片放到该目录下");
  9. Console.ReadKey(true);
  10. return;
  11. }
  12. if (!System.IO.Directory.Exists("NewImg")){
  13. System.IO.Directory.CreateDirectory("NewImg");
  14. }
  15. GetPath("Img");
  16. Console.ReadKey(true);
  17. }
  18.        //读取文件夹中所有文件
  19. static public void GetPath(string dir) {
  20. foreach (string d in Directory.GetFileSystemEntries(dir)) {
  21. if (File.Exists(d)) {
  22. FileInfo fi = new FileInfo(d);
  23. if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) {
  24. fi.Attributes = FileAttributes.Normal;
  25. }
  26. ChangeImageSize(dir);
  27. break;
  28. }else {
  29. DirectoryInfo d1 = new DirectoryInfo(d);
  30. GetPath(dir +"/" +d1.Name);
  31. }
  32. }
  33. }
  34. static public void ChangeImageSize(string dir) {
  35. string[] fileStrs = System.IO.Directory.GetFiles(dir);
  36. foreach (string s in fileStrs) {
  37. System.IO.FileInfo info = new System.IO.FileInfo(s);
  38. if (info.Extension == ".png" || info.Extension == ".jpg") {
  39. Image img = GetFile(s);
  40. Bitmap bit = GetNewSizeBitmap(img, size);
  41. SaveImage(bit, info.Name, info.Extension,dir);
  42. }
  43. }
  44. }
  45. static public Image GetFile(string path)
  46. {
  47. FileStream stream = File.OpenRead(path);
  48. int fileLength = 0;
  49. fileLength = (int)stream.Length;
  50. Byte[] image = new Byte[fileLength];
  51. stream.Read(image, 0, fileLength);
  52. System.Drawing.Image result = System.Drawing.Image.FromStream(stream);
  53. stream.Close();
  54. return result;
  55. }
  56. static public Bitmap GetNewSizeBitmap(Image img , double size){
  57. int newWidth = Convert.ToInt32(img.Width / size);
  58. int newHeight = Convert.ToInt32(img.Height / size);
  59. Size s = new Size(newWidth, newHeight);
  60. Bitmap newBit = new Bitmap(img, s);
  61. return newBit;
  62. }
  63. static public void SaveImage(Bitmap bit, string name, string ext, string dir)
  64. {
  65. if (!System.IO.Directory.Exists("NewImg\\" + dir)) {
  66. System.IO.Directory.CreateDirectory("NewImg\\" + dir);
  67. }
  68. bit.Save(@"NewImg\\" + dir + "\\" + name);
  69. bit.Dispose();
  70. Console.WriteLine("已处理:" + name);
  71. }
  72. }





读取文件夹中所有的文件

标签:ati   class   adk   size   byte   map   extension   pat   info   

原文地址:http://www.cnblogs.com/xiejunzhao/p/6517160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!