接口:
[HttpPost] public HttpResponseMessage UploadImg() { var result = new BaseResponse<List<ImageDto>>() { Data = new List<ImageDto>() }; result.Code = 1; HttpRequest request = System.Web.HttpContext.Current.Request; HttpFileCollection fileCollection = request.Files; var apiHost = $"https://{HttpContext.Current.Request.Url.Authority}"; if (fileCollection.Count > 0) { //"~/Upload/3m/UserUpload/ //源文件 string folderPath = "/Upload/3m/UserUpload/";//文件路徑 string hostFolderPath = HttpContext.Current.Server.MapPath(folderPath); if (!Directory.Exists(hostFolderPath)) { Directory.CreateDirectory(hostFolderPath); } var list = new List<string>() { "jpg", "jpeg", "png"}; //jpg/jpeg/bmp HttpPostedFile httpPostedFile = fileCollection[0]; ImageDto imgItem = new ImageDto(); // 獲取文件 不帶點 string fileExtension = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf('.') + 1).ToLower(); //string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件擴展名 帶點 if (!list.Contains(fileExtension)) { result.BuildError("上傳失敗:請上傳jpg,jpeg,png格式的圖片文件"); return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result); } var newFileName = $"{DateTime.Now:yyMMddhhmmss}{new System.Random().Next(100, 999)}.{fileExtension}"; //原圖 string filePath = $"{folderPath}{(folderPath.EndsWith("/") ? "" : "/")}{newFileName}"; string hostFilePath = $"{hostFolderPath}{(hostFolderPath.EndsWith(@"\") ? "" : @"\")}{newFileName}"; //存儲原圖 httpPostedFile.SaveAs(hostFilePath); string thumbfilePath = $"{folderPath}{(folderPath.EndsWith("/") ? "" : "/")}thumb_{newFileName}"; string thumbhostFilePath = $"{hostFolderPath}{(hostFolderPath.EndsWith(@"\") ? "" : @"\")}thumb_{newFileName}"; if (fileExtension == "jpg" || fileExtension == "jpeg") { //生成縮略圖 ImageToolsB.CompressImage(hostFilePath, thumbhostFilePath); } else { ImageToolsB.CompressionImage(hostFilePath, thumbhostFilePath, 25L); } if (File.Exists(thumbhostFilePath)) { if (File.Exists(hostFilePath)) { File.Delete(hostFilePath); } var id = _imbBll.Add(new UploadThumbImgEntity() { ImageUrl = thumbfilePath, CreateTime = DateTime.Now }); result.Data.Add(new ImageDto() { Id = id, ThumbImg = thumbfilePath, }); } } else { result.Error("獲取上傳文件失敗"); return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result); } return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result); }
工具方法:
public class ImageToolsB { /// <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(string sFile, string dFile, int flag = 90, int size = 500, bool sfsc = true) { //如果是第一次調用,原始圖像的大小小於要壓縮的大小,則直接復制文件,並且返回true FileInfo firstFileInfo = new FileInfo(sFile); if (sfsc == true && firstFileInfo.Length < size * 1024) { 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 = 0, sH = 0; //按比例縮放 Size tem_size = new Size(iSource.Width, iSource.Height); if (tem_size.Width > dHeight || tem_size.Width > dWidth) { if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.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(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; 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); } iSource.Dispose(); return true; } catch (Exception ex) { return false; } finally { iSource.Dispose(); ob.Dispose(); } } #region ImageCompress /// <summary> /// 圖片壓縮 ImageCompress.CompressionImage(fileSelect,@"d:\",50); /// </summary> /// <param name="imagePath">圖片文件路徑</param> /// <param name="targetFolder">保存文件夾</param> /// <param name="quality">壓縮質量</param> /// <param name="fileSuffix">壓縮后的文件名后綴(防止直接覆蓋原文件)</param> public static void CompressionImage(string imagePath, string targetFolder, long quality = 100, string fileSuffix = "compress") { if (!File.Exists(imagePath)) { throw new FileNotFoundException(); } if (!Directory.Exists(targetFolder)) { Directory.CreateDirectory(targetFolder); } var fileInfo = new FileInfo(imagePath); var fileName = fileInfo.Name.Replace(fileInfo.Extension, ""); var fileFullName = Path.Combine($"{targetFolder}", $"{fileName}_{fileSuffix}{fileInfo.Extension}"); var imageByte = CompressionImage(imagePath, quality); var ms = new MemoryStream(imageByte); var image = Image.FromStream(ms); image.Save(fileFullName); ms.Close(); ms.Dispose(); image.Dispose(); } /// <summary> /// 壓縮圖片 /// </summary> /// <param name="imagePath">壓縮前圖片全路徑</param> /// <param name="compressfilefullName">壓縮后圖片全路徑</param> /// <param name="quality">壓縮質量</param> public static void CompressionImage(string imagePath, string compressfilefullName, long quality = 100) { if (!File.Exists(imagePath)) { throw new FileNotFoundException(); } var imageByte = CompressionImage(imagePath, quality); var ms = new MemoryStream(imageByte); var image = Image.FromStream(ms); image.Save(compressfilefullName); ms.Close(); ms.Dispose(); image.Dispose(); } private static byte[] CompressionImage(string imagePath, long quality) { using (var fileStream = new FileStream(imagePath, FileMode.Open)) { using (var img = Image.FromStream(fileStream)) { using (var bitmap = new Bitmap(img)) { //var codecInfo = GetEncoder(img.RawFormat); //轉成jpg var codecInfo = GetEncoder(ImageFormat.Jpeg); var myEncoder = System.Drawing.Imaging.Encoder.Quality; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; using (var ms = new MemoryStream()) { bitmap.Save(ms, codecInfo, myEncoderParameters); myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); return ms.ToArray(); } } } } } private static ImageCodecInfo GetEncoder(ImageFormat format) { var codecs = ImageCodecInfo.GetImageDecoders(); return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid); } #endregion }
在壓縮png時,發現圖片文件沒有變小,反面變大了,
在網上找方法:C# Bitmap/png轉成jpg格式,壓縮圖片
//轉成jpg
var codecInfo = GetEncoder(ImageFormat.Jpeg);
string fileExtension = request.fileFullName.Substring(request.fileFullName.LastIndexOf('.') + 1).ToLower();
var fileName = request.fileFullName.Substring(request.fileFullName.LastIndexOf(@"\") + 1);
參考:https://www.cnblogs.com/testsec/p/6095729.html C# Bitmap/png轉成jpg格式,壓縮圖片
https://blog.csdn.net/nodeman/article/details/80661995 c# 無損高質量壓縮圖片代碼
https://www.cnblogs.com/wdw984/p/13112621.html C#進行圖片壓縮(對jpg壓縮效果最好)