图⽚base64转byte[]
/// <summary>
/// 保存base64图⽚,返回阿⾥云地址
/// </summary>
/// <param name="imgCode"></param>
/// <returns></returns>
private string SaveBase64Image(string imgCode)
{
string imgUrl = string.Empty;
if (!string.IsNullOrEmpty(imgCode))
{
Regex reg = new Regex(@"data:(image.+);base64,(.+)");
if (reg.IsMatch(imgCode))
{
var matchs = reg.Match(imgCode);
string contentType = matchs.Groups[1].Value;
string base64Code = matchs.Groups[2].Value;
string extendType = contentType.Replace("image/", "");
byte[] arr = Convert.FromBase64String(base64Code);//base64转byte[]
//var picture = _pictureService.InsertPicture(arr, extendType);
}
}
return imgUrl;
}
使⽤webservice返回图⽚内容,然后进⾏处理,为了⽅便,现在⼤多使⽤base64字符串的形式进⾏传递,这样就涉及到各种转换,现在将可能使⽤到的⽅法进⾏⼀个记
// <summary>
/// 将bytes数据转换为stream
/// </summary>
/// <param name="fileName">要保存成的⽂件路径</param>
param name/// <param name="dataBytes">要保存的数据</param>
/// <returns></returns>
public static Stream BytesToStream(string fileName, byte[] dataBytes)
{
if (dataBytes == null)
{
return null;
}
//MemoryStream ms = new MemoryStream(dataBytes);
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
fs.Write(dataBytes, 0, dataBytes.Length);
return fs;
}
}
/
// <summary>
/// Stream转换为⽂件
/// </summary>
/// <param name="stream"></param>
/// <param name="fileName"></param>
public static void StreamToFile(Stream stream, string fileName)
{
// 把 Stream 转换成 byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
// 把 byte[] 写⼊⽂件
// 把 byte[] 写⼊⽂件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
public static byte[] Base64ToBytes(string base64Img)
{
if (!string.IsNullOrEmpty(base64Img))
{
byte[] bytes = Convert.FromBase64String(base64Img);
return bytes;
}
return null;
}
/// <summary>
/// base64 转换为图⽚
/// </summary>
/// <param name="base64"></param>
/
// <returns></returns>
public static System.Drawing.Bitmap Base64ToImage(string base64) {
if (!string.IsNullOrEmpty(base64))
{
byte[] bytes = Base64ToBytes(base64);
if (bytes == null)
return null;
System.IO.MemoryStream ms = new MemoryStream();
ms.Write(bytes, 0, bytes.Length);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms); return bmp;
}
return null;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论