当前位置: 移动技术网 > IT编程>开发语言>.net > C# 图片格式转换的实例代码

C# 图片格式转换的实例代码

2020年08月04日  | 移动技术网IT编程  | 我要评论

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

涉及知识点

  • openfiledialog 打开文件对话框,用于选择文件,可以设置过滤后缀。
  • folderbrowserdialog 文件夹选择对话框,用于选择一个文件夹,可以新增。
  • imageformat 图片类型枚举。
  • bitmap 位图对象,包含对应的属性和内容。
  • 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# 图片格式转换的实例代码的详细内容,更多关于c# 图片格式转换的资料请关注移动技术网其它相关文章!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网