Fork me on GitHub

图片转换成base64编码文本

/// <summary>
/// 新建空间分布.
/// </summary>
/// <param name="input">参数.</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] SecurityRiskCrInput input)
{
var name = App.Configuration["JNPF_App:SystemPath"];
name.Replace("\\", "/");
var des = "";
var entity = input.Adapt<SecurityRiskEntity>();
int de = await _repository.AsSugarClient().Queryable<SecurityRiskEntity>().Where(it => it.CompanyCode.ToString() == _userManager.User.OrganizeId).CountAsync();
if (de > 19)
{
throw Oops.Oh(ErrorCode.COM1101);
}
entity.Id = SnowflakeIdHelper.NextId();
entity.CreateTime = DateTime.Now;
entity.CreateBy = _userManager.UserId;
entity.UpdateBy = _userManager.UserId;
entity.UpdateTime = DateTime.Now;
entity.DeleteMark = 0;
var data = await _repository.AsSugarClient().Queryable<BaseOrganizeEntity>().Where(it => it.Id.Equals(entity.CompanyCode)).Select(it => new
{
F_EnCode = it.EnCode,
}).FirstAsync();
if (data != null)
{
entity.OrgCode = data.F_EnCode;
}

foreach (var item in input.img)
{
entity.ImgName = item.name;
entity.Img = ImageToBase64(name + "//SystemFile//" + item.fileId);
}

var isOk = await _repository.AsSugarClient().Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
}

/// <summary>
/// 图片转换成base64编码文本.
/// </summary>
/// <summary>
/// Image 转成 base64.
/// </summary>
/// <param name="fileFullName">保存路径.</param>
private static string ImageToBase64(string fileFullName)
{
try
{

var suffix = fileFullName.Substring(fileFullName.LastIndexOf('.') + 1,
fileFullName.Length - fileFullName.LastIndexOf('.') - 1).ToLower();
var input = File.OpenRead(fileFullName);
var inputStream = new SKManagedStream(input);
var original = SKBitmap.Decode(inputStream);
var image = SKImage.FromBitmap(original);
var p = image.Encode(SKEncodedImageFormat.Png, 100);
var ms = new MemoryStream();
//保存到流
p.SaveTo(ms);

byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
string base64String = "data:image/" + suffix + ";base64," + Convert.ToBase64String(arr);
return base64String;
}

catch (Exception ex)
{
return ex.ToString();
}
}

posted @ 2023-03-22 17:08  残风飞雪  阅读(72)  评论(0编辑  收藏  举报

博客地址 - 创建于 2022年4月12日

这是一位.Net软件研发工程师的个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

致力于web网站开发工作,专注软件开发,关注互联网前沿技术与趋势。


Font Awesome Bootstrap中文网