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