C# Base64Helper
程序员文章站
2022-10-30 18:58:30
public static class Base64Helper { /// /// base64字符保存图片到本 /// /// 保存的图片完整路径 /// base64字符串 public static void Base64SaveImage(string filePath, str... ......
public static class base64helper { /// <summary> /// base64字符保存图片到本 /// </summary> /// <param name="filepath">保存的图片完整路径</param> /// <param name="base64string">base64字符串</param> public static void base64saveimage(string filepath, string base64string) { try { //如果base64是通过http传过来的,要注意其中的%、,、空格等转换,c#规定base64的长度必须是4的倍数,有个别语言是2的倍数,补上==。 base64string = base64string.trim().replace("%", "").replace(",", "").replace(" ", "+"); if (base64string.length % 4 != 0) { base64string += "=="; } byte[] arr2 = convert.frombase64string(base64string); using (memorystream ms2 = new memorystream(arr2)) { system.drawing.bitmap bmp2 = new system.drawing.bitmap(ms2); bmp2.save(filepath, system.drawing.imaging.imageformat.jpeg); bmp2.dispose(); } } catch (exception ex) { loghelper.writelog("图片保存异常:" + ex.tostring()); } } public static string imgtobase64string(string imagefilename) { try { bitmap bmp = new bitmap(imagefilename); memorystream ms = new memorystream(); bmp.save(ms, system.drawing.imaging.imageformat.jpeg); 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) { loghelper.writelog("图片读取异常:" + ex.tostring()); return null; } } public static string imagetobase64(string path) { byte[] bytes = getpicturedata(path); string base64 = convert.tobase64string(bytes); return base64; } public static bitmap base64toimage(string base64) { byte[] arr = convert.frombase64string(base64); memorystream ms = new memorystream(arr); bitmap bmp = new bitmap(ms); ms.close(); return bmp; } public static byte[] getpicturedata(string imagepath) { filestream fs = new filestream(imagepath, filemode.open); byte[] bydata = new byte[fs.length]; fs.read(bydata, 0, bydata.length); fs.close(); return bydata; } }
上一篇: sqlserver附加数据库出错
下一篇: 芝麻的好处有哪些 经常吃芝麻好处多多