C#实现图片格式转换的方法

发布时间:2020-08-04 09:09:44 作者:小猪
来源:亿速云 阅读:227

这篇文章主要讲解了C#实现图片格式转换的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

在日常工作中,经常需要不同格式的图片,有时还需要进行图片格式的相互转换,本文以一个简单的小例子,简述图片格式转换的常见方法,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

示例效果图

图片转换器的示例效果图如下:

C#实现图片格式转换的方法

核心代码

打开图片

/// <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#实现图片格式转换的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. GIF、SVG、PNG、图片格式转换
  2. 关于图片缩放的c#方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:如何解决Python pip使用超时问题

下一篇:C语言开发面试题有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》