| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316 |
- 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
- {
- //
- }
- }
- /// <summary>
- /// 无损压缩图片
- /// </summary>
- /// <param name="sFile">原图片地址</param>
- /// <param name="dFile">压缩后保存图片地址</param>
- /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
- /// <param name="size">压缩后图片的最大大小</param>
- /// <param name="sfsc">是否是第一次调用</param>
- /// <returns></returns>
- 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();
- }
- }
- /// <summary>
- /// 无损压缩图片
- /// </summary>
- /// <param name="fileStream">原图片</param>
- /// <param name="dFile">压缩后保存图片地址</param>
- /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
- /// <param name="size">压缩后图片的最大大小</param>
- /// <param name="sfsc">是否是第一次调用</param>
- /// <returns></returns>
- 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();
- }
- }
- }
- }
|