base64图片上传(需整合)

/// <summary>
/// 附件上传帮助类
/// </summary>
public class UploadFileHelper
{

/// <summary>
/// 返回由guid得到的数字
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
public static string SwitchGuid(Guid guid)
{
byte[] chars = guid.ToByteArray();
return BitConverter.ToInt64(chars, 0).ToString();
}

 

/// <summary>
/// 将图片旋转到正确位置
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static Image OrientationImage(Image image)
{
if (Array.IndexOf(image.PropertyIdList, 274) > -1)
{
var orientation = (int)image.GetPropertyItem(274).Value[0];
switch (orientation)
{
case 1:
// No rotation required.
break;
case 2:
image.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
image.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case 5:
image.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 7:
image.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
}
image.RemovePropertyItem(274);
}
return image;
}

/// <summary>
///base64编码的字符串转为图片
/// </summary>
/// <param name="strbase64">base64字符串</param>
/// <param name="fileBasedic">文件路径</param>
/// <param name="childFile">子目录</param>
/// <returns>返回路径,出错则返回""</returns>
public static string Base64StringToImage(string strbase64, string childFile, string fileBasedic)
{
try
{
string fileAddress = fileBasedic;
string FileName = DateTime.Now.ToString("yyyyMMdd") + SwitchGuid(Guid.NewGuid()) + "m";
//1.处理base64字符 data:image/png;base64,
string requestStrValue = strbase64.Substring(strbase64.IndexOf(',') + 1);//代表 图片 的base64编码数据
string requestFileExtension = strbase64.Split(new char[] { ';' })[0].Substring(strbase64.IndexOf('/') + 1);//获取后缀名
//图片上传路径 1头像2其他
string filePath = fileAddress + childFile + "/" + FileName + ".jpg";
// 如果目录不存在则要先创建
if (!Directory.Exists(fileAddress + childFile))
Directory.CreateDirectory(fileAddress + childFile);
// 保存新的图片文件
while (File.Exists(filePath))
System.IO.File.Delete(filePath);
//将Base64String转为图片并保存
byte[] arr2 = Convert.FromBase64String(requestStrValue);
using (MemoryStream ms2 = new MemoryStream(arr2))
{
//IOS处理图片旋转问题
using (Bitmap bmp2 = new Bitmap(ms2))
{
using (Image Newimg = OrientationImage(bmp2))
{
Newimg.Save(filePath);
}
}
}
return "/" + childFile + "/" + FileName + ".jpg";
}
catch (Exception)
{
return "";
}
}

posted @ 2022-04-13 09:19  兴趣就是天赋  阅读(243)  评论(0编辑  收藏  举报