C# 圖片格式轉換

在平常工做中,常常須要不一樣格式(JPG,PNG,BMP,GIF,ICO)的圖片,有時還須要進行圖片格式的相互轉換,本文以一個簡單的小例子,簡述圖片格式轉換的常見方法,僅供學習分享使用,若有不足之處,還請指正。ide

涉及知識點

  • OpenFileDialog 打開文件對話框,用於選擇文件,能夠設置過濾後綴。
  • FolderBrowserDialog 文件夾選擇對話框,用於選擇一個文件夾,能夠新增。
  • ImageFormat 圖片類型枚舉。
  • Bitmap 位圖對象,包含對應的屬性和內容。
  • Stream 流對象的基類。
  • FlowLayoutPanel 流式佈局容器,所添加的元素,以橫向或縱向依次排列。

 

示例效果圖

圖片轉換器的示例效果圖以下:佈局

 

核心代碼

 打開圖片學習

 1         /// <summary>
 2         /// 打開圖片
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnOpen_Click(object sender, EventArgs e)
 7         {
 8 
 9             this.fileDialog.Filter = fileFilter;
10             this.fileDialog.Multiselect = true;
11             this.fileDialog.CheckFileExists = true;
12             if (fileDialog.ShowDialog() == DialogResult.OK)
13             {
14                 string[] fileNames = this.fileDialog.FileNames;
15                 foreach(string fileName in fileNames)
16                 {
17                     Bitmap bmp = new Bitmap(fileName);
18                     //保存圖片名稱
19                     bmp.Tag = Path.GetFileNameWithoutExtension(fileName);
20                     PictureBox box = new PictureBox();
21                     box.Image = bmp;
22                     box.Width = 105;
23                     box.Height = 150;
24                     box.BorderStyle = BorderStyle.FixedSingle;
25                     box.Padding = new Padding(2);
26                     this.flowPnl.Controls.Add(box);
27                 }
28                 this.txtFile.Text = Path.GetDirectoryName(fileNames[0]);
29 
30             }
31         }
View Code

轉換圖片格式this

 1         /// <summary>
 2         /// 轉換圖片
 3         /// </summary>
 4         private void convertImage(string dir, string filter,Bitmap bmp)
 5         {
 6             string filePath = Path.Combine(dir, string.Format("{0}.{1}", bmp.Tag.ToString(), filter.ToLower()));
 7             switch (filter)
 8             {
 9                 case "JPG":
10                     bmp.Save(filePath, ImageFormat.Jpeg);
11                     break;
12                 case "PNG":
13                     bmp.Save(filePath, ImageFormat.Png);
14                     break;
15                 case "GIF":
16                     bmp.Save(filePath, ImageFormat.Gif);
17                     break;
18                 case "BMP":
19                     bmp.Save(filePath, ImageFormat.Bmp);
20                     break;
21                 case "ICO":
22                     Stream stream = File.Create(filePath);
23                     Icon icon = Icon.FromHandle(bmp.GetHicon());
24                     icon.Save(stream);       //   save the icon
25                     stream.Close();
26                     break;
27             }
28         }
View Code

若是須要示例的源碼,能夠點擊連接進行下載spa

源碼連接3d

備註

題李凝幽居

做者:賈島  唐代code

閒居少鄰並,草徑入荒園。
鳥宿池邊樹,僧敲月下門。
過橋分野色,移石動雲根。
暫去還來此,幽期不負言。orm

相關文章
相關標籤/搜索