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 "";
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章