这篇文章主要介绍了C# 图片格式转换的实例代码,文中讲解非常详细,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下
在日常工作中,经常需要不同格式的图片,有时还需要进行图片格式的相互转换,本文以一个简单的小例子,简述图片格式转换的常见方法,仅供学习分享使用,如有不足之处,还请指正。
涉及知识点
- 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# 图片格式转换的资料请关注得得之家其它相关文章!
沃梦达教程
本文标题为:C# 图片格式转换的实例代码
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
猜你喜欢
- Unity3D实现渐变颜色效果 2023-01-16
- c# 模拟线性回归的示例 2023-03-14
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- user32.dll 函数说明小结 2022-12-26
- Unity Shader实现模糊效果 2023-04-27
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- .NET CORE DI 依赖注入 2023-09-27
- 如何使用C# 捕获进程输出 2023-03-10
- Oracle中for循环的使用方法 2023-07-04