轻量级前端框架助力开发者提升项目效率与性能
637
2022-09-19
C# 图片与Base64的相互转化(count)
public ActionResult UploadSignature2(string src_data)
{
Class1.Base64StrToImage(src_data, "C:\\Users\\45448\\Desktop\\1\\"+ DateTime.Now.ToString("yyyyMMddHHss") + ".png");
return Json(1, JsonRequestBehavior.AllowGet);
}
///
/// 将Base64字符串转换为图片并保存到本地
///
/// base64字符串
/// 图片保存地址,如:/Content/Images/10000.png
///
public static bool Base64StrToImage(string base64Str, string savePath)
{
var ret = true;
try
{
base64Str = base64Str.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "")
.Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", ""); //将base64头部信息替换
var bitmap = Base64StrToImage(base64Str);
if (bitmap != null)
{
//创建文件夹
var folderPath = savePath.Substring(0, savePath.LastIndexOf('\\'));
////FileHelper.CreateDir(folderPath);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
//图片后缀格式
var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1,
savePath.Length - savePath.LastIndexOf('.') - 1).ToLower();
var suffixName = suffix == "png"
? ImageFormat.Png
: suffix == "jpg" || suffix == "jpeg"
? ImageFormat.Jpeg
: suffix == "bmp"
? ImageFormat.Bmp
: suffix == "gif"
? ImageFormat.Gif
: ImageFormat.Jpeg;
//这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
var bmpNew = new Bitmap(bitmap);
bmpNew.Save(savePath, suffixName);
bmpNew.Dispose();
bitmap.Dispose();
}
else
{
ret = false;
}
}
catch (Exception ex)
{
ret = false;
}
return ret;
}
复制代码
复制代码
///
/// Image 转成 base64
///
///
public static string ImageToBase64(string fileFullName)
{
try
{
Bitmap bmp = new Bitmap(fileFullName);
MemoryStream ms = new MemoryStream();
var suffix = fileFullName.Substring(fileFullName.LastIndexOf('.') + 1,
fileFullName.Length - fileFullName.LastIndexOf('.') - 1).ToLower();
var suffixName = suffix == "png"
? ImageFormat.Png
: suffix == "jpg" || suffix == "jpeg"
? ImageFormat.Jpeg
: suffix == "bmp"
? ImageFormat.Bmp
: suffix == "gif"
? ImageFormat.Gif
: ImageFormat.Jpeg;
bmp.Save(ms, suffixName);
byte[] arr = new byte[ms.Length]; ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length); ms.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return null;
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~