本文實例講述了C#簡易圖片格式轉換器實現方法。分享給大家供大家參考,具體如下:
在窗體上放一個picturebox,menustrip.在菜單上鍵入兩個按鈕,分別為“文件”,“格式”。在“文件”下創建一個子菜單“打開”,name為menuOpen,在“格式”下創建一個子菜單“轉換格式”,name為menuConvert.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Imaging; using System.IO; namespace WindowsFormsApplication51 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string filename = "";//文件名 //文件菜單下的“打開”按鈕 private void menuOpen_Click(object sender, EventArgs e) { OpenFileDialog of = new OpenFileDialog(); of.Title = "打開文件"; of.Filter = "圖像文件|*.bmp;*.gif;*.jpg;*.png"; if (of.ShowDialog() == DialogResult.OK) { filename = of.FileName; pictureBox1.Image = Image.FromFile(filename); pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } } //“轉換格式”按鈕 private void menuConvert_Click(object sender, EventArgs e) { ImageFormat[] format = { ImageFormat.Bmp, ImageFormat.Gif, ImageFormat.Jpeg, ImageFormat.Png }; //ImageFormat是using System.Drawing.Imaging;下的方法,用來指定文件的格式 Image image = Image.FromFile(filename); SaveFileDialog sf = new SaveFileDialog(); sf.InitialDirectory = Path.GetDirectoryName(filename);//system.io下的path里的GetDirectoryName()方法可以返回指定路徑字符串的目錄信息 sf.FileName = Path.GetFileNameWithoutExtension(filename);//返回不具有擴展名的指定路徑字符串的文件名 sf.Filter = "位圖(*.bmp)|*.bmp|交換圖像格式(*.gif)|*.gif|聯合圖像專家組(*.jpg)|*.jpg;*.jpeg|可移植網絡圖形(*.png)|*.png"; if (sf.ShowDialog() == DialogResult.OK) { image.Save(sf.FileName, format[sf.FilterIndex - 1]);//選擇下拉表的第一個,則對應數組format[0] MessageBox.Show("格式轉換成功", "消息"); } else { MessageBox.Show("格式轉換不成功", "消息"); } } } }
效果圖如下:
打開一幅jpg圖,轉換為bitmap
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答