批量压缩图片
// See https://aka.ms/new-console-template for more information using ReduceImage; Console.WriteLine("Hello, World!"); string folderPath = "C:\\Users\\shiningrise\\Desktop\\fsdownload\\UploadFiles"; // 将此处替换为要遍历的文件夹路径 Bianli(folderPath); void Bianli(string path) { List<string> temp = new List<string>(); temp.Add(path); for (int i = 0; i < temp.Count; i++) { if (File.Exists(temp[i])) { continue; } else { List<string> dirs = new List<string>(Directory.EnumerateDirectories(temp[i])); foreach (var dir in dirs) { temp.Add(dir); } List<string> files = new List<string>(Directory.EnumerateFiles(temp[i])); foreach (string file in files) { temp.Add(file); } } } foreach (string pathTemp in temp) { if (File.Exists(pathTemp)) Img.ReduceImage(pathTemp, 768, 254); Console.WriteLine(pathTemp); } }
using System; using System.Net; using System.IO; using System.Text; using System.Drawing; namespace ReduceImage { /// <summary> /// 下载远程图片保存到本地地址 /// </summary> public class Img { public static void ReduceImage(string imageFile, int toWidth, int toHeight) { try { Image originalImage = Image.FromFile(imageFile); if (toWidth <= 0 && toHeight <= 0) { return; } else if (toWidth > 0 && toHeight > 0) { if (originalImage.Width < toWidth && originalImage.Height < toHeight) return; } else if (toWidth <= 0 && toHeight > 0) { if (originalImage.Height < toHeight) return; toWidth = originalImage.Width * toHeight / originalImage.Height; } else if (toHeight <= 0 && toWidth > 0) { if (originalImage.Width < toWidth) return; toHeight = originalImage.Height * toWidth / originalImage.Width; } Image toBitmap = new Bitmap(toWidth, toHeight); try { using (Graphics g = Graphics.FromImage(toBitmap)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage(originalImage, new Rectangle(0, 0, toWidth, toHeight), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel); originalImage.Dispose(); toBitmap.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png); toBitmap.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (originalImage != null) originalImage.Dispose(); if (toBitmap != null) toBitmap.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2019-04-10 docker-mysql-cron-backup不能执行任务
2017-04-10 DbScopeFactory