C#图片转换成文本,和文本转换成图片的方法一级如何调用

评价:
0
(0用户)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
/// <summary>
/// 用于图片文本之间转换的实体类
/// </summary>
public class SerializeObjectToString
{
/// <summary>
/// 将Object类型对象(注:必须是可序列化的对象)转换为二进制序列字符串
/// </summary>
/// <param name=”obj”></param>
/// <returns></returns>
public static string SerializeObject(object obj)
{
IFormatter formatter = new BinaryFormatter();
string result = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, obj);
byte[] byt = new byte[stream.Length];
byt = stream.ToArray();
//result = Encoding.UTF8.GetString(byt, 0, byt.Length);
result = Convert.ToBase64String(byt);
stream.Flush();
}
return result;
}
/// <summary>
/// 将二进制序列字符串转换为Object类型对象
/// </summary>
/// <param name=”str”></param>
/// <returns></returns>
public object DeserializeObject(string str)
{
IFormatter formatter = new BinaryFormatter();
//byte[] byt = Encoding.UTF8.GetBytes(str);
byte[] byt = Convert.FromBase64String(str);
object obj = null;
using (Stream stream = new MemoryStream(byt, 0, byt.Length))
{
obj = formatter.Deserialize(stream);
}
return obj;
}
}
}

//调用
//1.文本转换成图片
if (string.IsNullOrWhiteSpace(objBook.BookImage)) pbBookImage.BackgroundImage = null;
else pbBookImage.BackgroundImage = (Image)new Common.SerializeObjectToString().DeserializeObject(objBook.BookImage);
//2.图片转换成文本
//图片转换成文本
if (pbBookImage.BackgroundImage == null) objBook.BookImage = null;
else objBook.BookImage = Common.SerializeObjectToString.SerializeObject(pbBookImage.BackgroundImage);

注册并通过认证的用户才可以进行评价!

admin:支持一下,感谢分享!,+10,  

发表评论