C# 圖片格式轉(zhuǎn)換的實(shí)例代碼
更新時間:2020年08月03日 15:05:29 作者:Alan.hsiang
這篇文章主要介紹了C# 圖片格式轉(zhuǎn)換的實(shí)例代碼,文中講解非常詳細(xì),幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下
在日常工作中,經(jīng)常需要不同格式的圖片,有時還需要進(jìn)行圖片格式的相互轉(zhuǎn)換,本文以一個簡單的小例子,簡述圖片格式轉(zhuǎn)換的常見方法,僅供學(xué)習(xí)分享使用,如有不足之處,還請指正。
涉及知識點(diǎn)
- OpenFileDialog 打開文件對話框,用于選擇文件,可以設(shè)置過濾后綴。
- FolderBrowserDialog 文件夾選擇對話框,用于選擇一個文件夾,可以新增。
- ImageFormat 圖片類型枚舉。
- Bitmap 位圖對象,包含對應(yīng)的屬性和內(nèi)容。
- Stream 流對象的基類。
- FlowLayoutPanel 流式布局容器,所添加的元素,以橫向或縱向依次排列。
示例效果圖
圖片轉(zhuǎn)換器的示例效果圖如下:

核心代碼
打開圖片
/// <summary>
/// 打開圖片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpen_Click(object sender, EventArgs e)
{
this.fileDialog.Filter = fileFilter;
this.fileDialog.Multiselect = true;
this.fileDialog.CheckFileExists = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string[] fileNames = this.fileDialog.FileNames;
foreach(string fileName in fileNames)
{
Bitmap bmp = new Bitmap(fileName);
//保存圖片名稱
bmp.Tag = Path.GetFileNameWithoutExtension(fileName);
PictureBox box = new PictureBox();
box.Image = bmp;
box.Width = 105;
box.Height = 150;
box.BorderStyle = BorderStyle.FixedSingle;
box.Padding = new Padding(2);
this.flowPnl.Controls.Add(box);
}
this.txtFile.Text = Path.GetDirectoryName(fileNames[0]);
}
}
轉(zhuǎn)換圖片格式
/// <summary>
/// 轉(zhuǎn)換圖片
/// </summary>
private void convertImage(string dir, string filter,Bitmap bmp)
{
string filePath = Path.Combine(dir, string.Format("{0}.{1}", bmp.Tag.ToString(), filter.ToLower()));
switch (filter)
{
case "JPG":
bmp.Save(filePath, ImageFormat.Jpeg);
break;
case "PNG":
bmp.Save(filePath, ImageFormat.Png);
break;
case "GIF":
bmp.Save(filePath, ImageFormat.Gif);
break;
case "BMP":
bmp.Save(filePath, ImageFormat.Bmp);
break;
case "ICO":
Stream stream = File.Create(filePath);
Icon icon = Icon.FromHandle(bmp.GetHicon());
icon.Save(stream); // save the icon
stream.Close();
break;
}
}
如果需要示例的源碼,可以點(diǎn)擊鏈接進(jìn)行下載
以上就是C# 圖片格式轉(zhuǎn)換的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于c# 圖片格式轉(zhuǎn)換的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C# 進(jìn)行圖片壓縮的示例代碼(對jpg壓縮效果最好)
這篇文章主要介紹了C# 進(jìn)行圖片壓縮的示例代碼,幫助大家更好的利用c# 處理圖片,提高辦公效率,感興趣的朋友可以了解下2020-11-11

