最近项目中遇到需要json传输上百个图标
进行了多种二进制转String的尝试,最终转得的String完全不对
自己估计是编码格式问题,查找资源发现basic64专做二进制数组和String之间的装换,
将Byte与字符相互装换
以下是C#实现的 json可用的 图片转String String转图片 的代码
/// <summary>Convert bitmap to Base64 String
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static String Jpeg2String(Bitmap bitmap)
{
using (Stream stream = new System.IO.MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
Byte[] picData = new byte[stream.Length];
stream.Read(picData, 0, picData.Length);
String sbmp = System.Convert.ToBase64String(picData);
return sbmp;
}
}
/// <summary> Convert base64 String to Jpeg
/// </summary>
/// <param name="base64Str"></param>
/// <returns></returns>
public static Bitmap GetBitMap(String base64Str)
{
if (!String.IsNullOrEmpty(base64Str))
{
using (Stream stream = new MemoryStream())
{
byte[] picData = System.Convert.FromBase64String(base64Str);
stream.Write(picData, 0, picData.Length);
stream.Seek(0, SeekOrigin.Begin);
Bitmap bitmap = new Bitmap(stream);
return bitmap;
}
}
return null;
}