///
///根据文件类型和文件名返回新路径///
/// 文件类型
/// 文件名/回传新的相对路径
/// 全新文件绝对路径
public static string CreatePath(FileType type, ref stringfileName)
{string path1 = $"{RootPath}{Enum.GetName(typeof(FileType), type)}/";var path = $"{AppContext.BaseDirectory}{path1}";//检查上传的物理路径是否存在,不存在则创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}string name = $"{DateTime.Now:yyyyMMddHHmmssff}.{GetFileExt(fileName)}";
fileName= $"{path1}{name}";return $"{path}{name}";
}///
///取小写文件名后缀///
/// 文件名
/// 返回小写后缀,不带“.”
public static string GetFileExt(stringname)
{return name.Split(".").Last().ToLower();
}///
///是否为图片文件///
/// 文件扩展名,不含“.”
public static bool IsImage(stringfileExt)
{
ArrayList al= new ArrayList{"bmp","jpeg","jpg","gif","png","ico"};returnal.Contains(fileExt);
}///
///检查是否允许文件///
/// 文件后缀
/// 允许文件数组
public static bool CheckFileExt(string fileExt, string[] allowExt)
{return allowExt.Any(t => t ==fileExt);
}///
///制作缩略图///
/// 图片对象
/// 新图路径
/// 最大宽度
/// 最大高度
public static void ThumbImg(Image original, string newFileName, int maxWidth, intmaxHeight)
{
Size newSize=ResizeImage(original.Width, original.Height, maxWidth, maxHeight);using (Image displayImage = newBitmap(original, newSize))
{try{
displayImage.Save(newFileName, original.RawFormat);
}finally{
original.Dispose();
}
}
}///
///制作缩略图///
/// 文件名
/// 新图路径
/// 最大宽度
/// 最大高度
public static void ThumbImg(string fileName, string newFileName, int maxWidth, intmaxHeight)
{byte[] imageBytes =File.ReadAllBytes(fileName);
Image img= Image.FromStream(newMemoryStream(imageBytes));
ThumbImg(img, newFileName, maxWidth, maxHeight);
}///
///计算新尺寸///
/// 原始宽度
/// 原始高度
/// 最大新宽度
/// 最大新高度
///
private static Size ResizeImage(int width, int height, int maxWidth, intmaxHeight)
{if (maxWidth <= 0)
maxWidth=width;if (maxHeight <= 0)
maxHeight=height;decimal MAX_WIDTH =maxWidth;decimal MAX_HEIGHT =maxHeight;decimal ASPECT_RATIO = MAX_WIDTH /MAX_HEIGHT;intnewWidth, newHeight;decimal originalWidth =width;decimal originalHeight =height;if (originalWidth > MAX_WIDTH || originalHeight >MAX_HEIGHT)
{decimalfactor;if (originalWidth / originalHeight >ASPECT_RATIO)
{
factor= originalWidth /MAX_WIDTH;
newWidth= Convert.ToInt32(originalWidth /factor);
newHeight= Convert.ToInt32(originalHeight /factor);
}else{
factor= originalHeight /MAX_HEIGHT;
newWidth= Convert.ToInt32(originalWidth /factor);
newHeight= Convert.ToInt32(originalHeight /factor);
}
}else{
newWidth=width;
newHeight=height;
}return newSize(newWidth, newHeight);
}///
///得到图片格式///
/// 文件名称
///
public static ImageFormat GetFormat(stringname)
{string ext =GetFileExt(name);switch(ext)
{case "ico":returnImageFormat.Icon;case "bmp":returnImageFormat.Bmp;case "png":returnImageFormat.Png;case "gif":returnImageFormat.Gif;default:returnImageFormat.Jpeg;
}
}