C#简易图片格式转换器实现方法

时间:2022-02-15 12:12:59

本文实例讲述了C#简易图片格式转换器实现方法。分享给大家供大家参考,具体如下:

在窗体上放一个picturebox,menustrip.在菜单上键入两个按钮,分别为“文件”,“格式”。在“文件”下创建一个子菜单“打开”,name为menuOpen,在“格式”下创建一个子菜单“转换格式”,name为menuConvert. 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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#简易图片格式转换器实现方法

C#简易图片格式转换器实现方法

希望本文所述对大家C#程序设计有所帮助。