using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using IwbZero.ToolCommon.LogHelpers; namespace IwbZero.ToolCommon.FileHelpers { public static class FileUpload { private static string GetFileExt(string fileName) { string fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1, fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1); return fileExt.ToLower(); } public static string Base64ToFile(this string base64Str, string fileName, string filePath, string fileExt) { fileName = $"{fileName}.{fileExt}"; string lcRetVal = Base64ToFile(base64Str, fileName, filePath); return lcRetVal; } public static string Base64ToFile(this string base64Str, string fileName, string filePath) { string lcRetVal = "error@"; try { filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath); filePath = filePath.EndsWith("/") ? filePath : (filePath + "/"); string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); byte[] bytes = Convert.FromBase64String(base64Str); using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create, FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); fs.Close(); } lcRetVal = filePath + fileName; } catch (Exception e) { typeof(FileUpload).LogError(e); lcRetVal += "文件上传异常。"; } return lcRetVal; } public static string Base64ToPng(this string base64Str, string fileName, string filePath = "/Image") { string lcRetVal = "error@"; try { fileName = $"{fileName}-{DateTime.Now:yyMMddHHmmss}{new Random().Next(1000, 9999)}.png"; filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath); filePath = filePath.EndsWith("/") ? filePath : (filePath + "/"); string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); byte[] bytes = Convert.FromBase64String(base64Str); using (MemoryStream ms = new MemoryStream(bytes)) { var img = Image.FromStream(ms); img.Save($"{path}{fileName}"); } lcRetVal = filePath + fileName; } catch (Exception e) { typeof(FileUpload).LogError(e); lcRetVal += "文件上传异常。"; } return lcRetVal; } public static void DeleteFile(this string filePath) { try { filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath); string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}"; if (File.Exists(path)) File.Delete(path); } catch { // } } /// /// 无损压缩图片 /// /// 原图片地址 /// 压缩后保存图片地址 /// 压缩质量(数字越小压缩率越高)1-100 /// 压缩后图片的最大大小 /// 是否是第一次调用 /// public static bool CompressImage(this string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true) { //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true FileInfo firstFileInfo = new FileInfo(sFile); if (sfsc && firstFileInfo.Length < size * 1024) { if (File.Exists(dFile)) { File.Delete(dFile); } firstFileInfo.CopyTo(dFile); return true; } Image iSource = Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; int dHeight = iSource.Height / 2; int dWidth = iSource.Width / 2; int sW, sH; //按比例缩放 Size temSize = new Size(iSource.Width, iSource.Height); if (temSize.Width > dHeight || temSize.Width > dWidth) { if ((temSize.Width * dHeight) > (temSize.Width * dWidth)) { sW = dWidth; sH = (dWidth * temSize.Height) / temSize.Width; } else { sH = dHeight; sW = (temSize.Width * dHeight) / temSize.Height; } } else { sW = temSize.Width; sH = temSize.Height; } //新建第二个bitmap类型的bmp2变量,我这里是根据我的程序需要设置的。 Bitmap ob = new Bitmap(dWidth, dHeight, PixelFormat.Format16bppRgb555); Graphics g = Graphics.FromImage(ob); //Bitmap ob = new Bitmap(dWidth, dHeight); //Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //将第一个bmp拷贝到bmp2中 //Bitmap ob = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format16bppRgb555); //Graphics draw = Graphics.FromImage(ob); //draw.DrawImage(bmp, 0, 0); //draw.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegIcIinfo = null; var ext = GetFileExt(dFile)?.ToUpper(); foreach (var t in arrayIci) { if (t.FormatDescription.Equals(ext)) { jpegIcIinfo = t; break; } } if (jpegIcIinfo != null) { ob.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径 FileInfo fi = new FileInfo(dFile); if (fi.Length > 1024 * size) { flag = flag - 10; CompressImage(sFile, dFile, flag, size, false); } } else { ob.Save(dFile, tFormat); } return true; } catch (Exception e) { typeof(FileUpload).LogError(e); return false; } finally { iSource.Dispose(); //bmp.Dispose(); ob.Dispose(); } } /// /// 无损压缩图片 /// /// 原图片 /// 压缩后保存图片地址 /// 压缩质量(数字越小压缩率越高)1-100 /// 压缩后图片的最大大小 /// 是否是第一次调用 /// public static bool CompressImage(this MemoryStream fileStream, string dFile, int flag = 90, int size = 300, bool sfsc = true) { //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true Image iSource = Image.FromStream(fileStream); if (sfsc && fileStream.Length < size * 1024) { iSource.Save(dFile); return true; } ImageFormat tFormat = iSource.RawFormat; int dHeight = iSource.Height / 2; int dWidth = iSource.Width / 2; int sW, sH; //按比例缩放 Size temSize = new Size(iSource.Width, iSource.Height); if (temSize.Width > dHeight || temSize.Width > dWidth) { if ((temSize.Width * dHeight) > (temSize.Width * dWidth)) { sW = dWidth; sH = (dWidth * temSize.Height) / temSize.Width; } else { sH = dHeight; sW = (temSize.Width * dHeight) / temSize.Height; } } else { sW = temSize.Width; sH = temSize.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegIcIinfo = null; foreach (var t in arrayIci) { if (t.FormatDescription.Equals("JPEG")) { jpegIcIinfo = t; break; } } if (jpegIcIinfo != null) { ob.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径 FileInfo fi = new FileInfo(dFile); if (fi.Length > 1024 * size) { flag = flag - 10; CompressImage(fileStream, dFile, flag, size, false); } } else { ob.Save(dFile, tFormat); } return true; } catch { return false; } finally { iSource.Dispose(); ob.Dispose(); } } } }