C#实现的图片、string相互转换类分享
2015-03-27 11:45
1206 查看
C#中,Image为源自 Bitmap 和 Metafile 的类提供功能的抽象基类,也就是说更通用,当我们用Image.FromFile("xxx")时创建出来的是Image的某个派生类实体,所以我用Image作为参数,而不是Bitmap之类的。
图片在于string转换的时候中间借助于MemorySteam和Byte数组,下面是我写的FormatChange类,里面两个互相转换的过程。当然这里面也就包含了图片与Byte[]数组的相互转换喽。
class FormatChange { public static string ChangeImageToString(Image image) { try { MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); string pic = Convert.ToBase64String(arr); return pic; } catch (Exception) { return "Fail to change bitmap to string!"; } } public static Image ChangeStringToImage(string pic) { try { byte[] imageBytes = Convert.FromBase64String(pic); //读入MemoryStream对象 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); memoryStream.Write(imageBytes, 0, imageBytes.Length); //转成图片 Image image = Image.FromStream(memoryStream); return image; } catch (Exception) { Image image = null; return image; } } }
您可能感兴趣的文章:
- C#判断一个String是否为数字类型
- C#实现去除Strings中空格的方法
- C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换
- C#中string用法实例详解
- C# string格式的日期时间字符串转为DateTime类型的方法
- ASP.NET(C#) String, StringBuilder 与 StringWriter性能比较
- C#中String类常用方法汇总
- C#中的DataSet、string、DataTable、对象转换成Json的实现代码
- C#中把字符串String转换为整型Int的小例子
- c#基础系列之System.String的深入理解
相关文章推荐
- C#实现String类型和json之间的相互转换功能示例
- C#中图片BYTE[]和base64string的相互转换
- java实现图片image和字符串String的相互转换
- c#实现图片与字节流相互转换的代码
- BCB实现BMP图片的RGB分解,BMP与JPG格式的相互转换
- c# string和byte数组相互转换
- C#中string[]数组和list<string>泛型的相互转换
- c#中 uint--byte[]--char[]--string相互转换汇总
- c#中 uint--byte[]--char[]--string相互转换汇总
- c#中 uint--byte[]--char[]--string相互转换汇总
- [转]c#中 uint--byte[]--char[]--string相互转换汇总
- c#中 uint--byte[]--char[]--string相互转换汇总
- c#中 uint--byte[]--char[]--string相互转换汇总
- 实现C#和VB.net之间的相互转换
- c#中 uint--byte[]--char[]--string相互转换汇总
- c#中 uint--byte[]--char[]--string相互转换
- c#中 uint--byte[]--char[]--string相互转换汇总
- C#中Brush、Color、String相互转换
- 实现C#和VB.net之间的相互转换(马辉)
- C#实现图片文件到数据流再到图片文件的转换