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
{
///
/// 用于图片文本之间转换的实体类
///
public class SerializeObjectToString
{
///
/// 将Object类型对象(注:必须是可序列化的对象)转换为二进制序列字符串
///
///
///
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;
}
///
/// 将二进制序列字符串转换为Object类型对象
///
///
///
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);