这篇文章主要讲解了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#实现图片格式转换的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。