Base64与图片互转
作者:互联网
base64 to 图片
https://github.com/ITAgnesmeyer/EasyBase64ToImage
public class ImageToString { /// <summary> /// Converts Image to Base64 /// </summary> /// <param name="image">Image</param> /// <returns>Base64 String</returns> public static string ImageToBase64(Image image) { using (var m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); string base64String = Convert.ToBase64String(imageBytes); return base64String; } } /// <summary> /// Converts Base64-String to Image /// </summary> /// <param name="base64String"></param> /// <returns></returns> public static Image Base64ToImage(string base64String) { byte[] imageBytes = Convert.FromBase64String(base64String); using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { ms.Write(imageBytes, 0, imageBytes.Length); Image image = Image.FromStream(ms); return image; } } }
基于上述代码,然后以bitmap存储相应格式(Image直接存储jpg有点儿问题,在system.drawing中会报错。)
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
public Task<int> AddNewGembaWalk(GembaWalkModel gembaWalkModel) { gembaWalks.Add(gembaWalkModel); string typeimg = gembaWalkModel.Image1.Split(';')[0].Split('/')[1];//get img format string base64 = gembaWalkModel.Image1.Replace("data:image/" + typeimg + ";base64,", string.Empty); //replace format, only need the base64 string Image image = EasyBase64ToImage.ImageToString.Base64ToImage(base64); Bitmap bitmap = new Bitmap(image); bitmap.Save($"C:\\Temp\\Img\\{DateTime.Now.ToString("yyyyMMdd hhmmssff")}.{typeimg}", image.RawFormat); return Task.FromResult(0); }
标签:base64String,base64,string,Image,Base64,imageBytes,互转,image,图片 来源: https://www.cnblogs.com/chengcanghai/p/16595210.html