C#如何批量修改圖片尺寸和DPI
更新時(shí)間:2025年05月30日 09:28:33 作者:綠葉白墻
這篇文章主要介紹了C#批量修改圖片尺寸和DPI方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
C#批量修改圖片尺寸和DPI
讀取指定路徑下的圖片文件,修改圖片尺寸和pdi
我的文件夾下都是圖片
如果是混合的文件,自己寫個(gè)后綴名過濾函數(shù)就行,或者修改 GetFiles 過濾參數(shù) “*”.
string[] filedir = Directory.GetFiles(Root, "*.png", SearchOption.AllDirectories);
private void button1_Click(object sender, EventArgs e) { string Root = this.textBox1.Text.Trim(); // 讀取文件夾下的所有文件 (方法一) string[] filedir = Directory.GetFiles(Root, "*", SearchOption.AllDirectories); foreach (string fileName in filedir) { ChagePicDPI(fileName); } 方法二 //DirectoryInfo folder = new DirectoryInfo(Root); //foreach (FileInfo file in folder.GetFiles("*")) //{ // // 修改圖片dpi // ChagePicDPI(file); //} MessageBox.Show("ok"); } private void ChagePicDPI(string fileName) { int newWidth = 400; // 固定圖像寬度 int DPI = 1200; // 圖像DPI using (Bitmap oldBitmap = new Bitmap(fileName)) { int newHeight = Convert.ToInt32(1.0 * oldBitmap.Height * newWidth / oldBitmap.Width); // 圖像高度按照寬度等比變化 using (Bitmap newBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(newBitmap)) { g.Clear(System.Drawing.Color.White); // 背景白色 g.DrawImage(oldBitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height)); newBitmap.SetResolution(DPI, DPI); // 設(shè)置DPI string newFileName = fileName.Replace("D:\\圖形", "C:\\Users\\Administrator\\Desktop\\11111"); // 替換文件路徑 string dir = Path.GetDirectoryName(newFileName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } newBitmap.Save(newFileName, oldBitmap.RawFormat); // 保存圖片,按照?qǐng)D片原始格式保存 } } } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#更新文本框textbox數(shù)據(jù)同時(shí)刪除舊數(shù)據(jù)問題
這篇文章主要介紹了C#更新文本框textbox數(shù)據(jù)同時(shí)刪除舊數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04windows系統(tǒng)下,如何在C#程序中自動(dòng)安裝字體
在Windows系統(tǒng)中,原有自帶的字體樣式有限,有時(shí)候我們的程序會(huì)使用到個(gè)別稀有或系統(tǒng)不自帶的字體。因此我們需要將字體打包到程序中,當(dāng)程序啟動(dòng)時(shí),檢測(cè)系統(tǒng)是否有該字體,如果沒有則安裝該字體,也可以動(dòng)態(tài)加載字體。2020-11-11Visual C#類的定義及實(shí)現(xiàn)方法實(shí)例解析
這篇文章主要介紹了Visual C#類的定義及實(shí)現(xiàn)方法實(shí)例解析,對(duì)于新手來說有不錯(cuò)的借鑒學(xué)習(xí)價(jià)值,需要的朋友可以參考下2014-07-07C# BackgroundWorker組件學(xué)習(xí)入門介紹
一個(gè)程序中需要進(jìn)行大量的運(yùn)算,并且需要在運(yùn)算過程中支持用戶一定的交互,為了獲得更好的用戶體驗(yàn),使用BackgroundWorker來完成這一功能2013-10-10C#集合根據(jù)對(duì)象的某個(gè)屬性進(jìn)行去重的代碼示例
當(dāng)根據(jù)對(duì)象的Name屬性進(jìn)行去重時(shí),你可以使用以下三種方法:使用Distinct方法和自定義比較器、使用LINQ的GroupBy方法,以及使用HashSet,下面給大家介紹C#集合根據(jù)對(duì)象的某個(gè)屬性進(jìn)行去重的代碼示例,感興趣的朋友一起看看吧2024-03-03