C#如何批量修改圖片尺寸和DPI
更新時間:2025年05月30日 09:28:33 作者:綠葉白墻
這篇文章主要介紹了C#批量修改圖片尺寸和DPI方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
C#批量修改圖片尺寸和DPI
讀取指定路徑下的圖片文件,修改圖片尺寸和pdi
我的文件夾下都是圖片
如果是混合的文件,自己寫個后綴名過濾函數(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); // 保存圖片,按照圖片原始格式保存
}
}
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#更新文本框textbox數(shù)據(jù)同時刪除舊數(shù)據(jù)問題
這篇文章主要介紹了C#更新文本框textbox數(shù)據(jù)同時刪除舊數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
windows系統(tǒng)下,如何在C#程序中自動安裝字體
在Windows系統(tǒng)中,原有自帶的字體樣式有限,有時候我們的程序會使用到個別稀有或系統(tǒng)不自帶的字體。因此我們需要將字體打包到程序中,當(dāng)程序啟動時,檢測系統(tǒng)是否有該字體,如果沒有則安裝該字體,也可以動態(tài)加載字體。2020-11-11
C# BackgroundWorker組件學(xué)習(xí)入門介紹
一個程序中需要進(jìn)行大量的運算,并且需要在運算過程中支持用戶一定的交互,為了獲得更好的用戶體驗,使用BackgroundWorker來完成這一功能2013-10-10
C#集合根據(jù)對象的某個屬性進(jìn)行去重的代碼示例
當(dāng)根據(jù)對象的Name屬性進(jìn)行去重時,你可以使用以下三種方法:使用Distinct方法和自定義比較器、使用LINQ的GroupBy方法,以及使用HashSet,下面給大家介紹C#集合根據(jù)對象的某個屬性進(jìn)行去重的代碼示例,感興趣的朋友一起看看吧2024-03-03

