文件上传,服务端压缩文件方法,重点是png与gif图片的压缩,保证了透明度与动画

  1 /// <summary>
  2     /// 上传文件帮助类
  3     /// </summary>
  4     public class ImageUploadHelper
  5     {
  6 
  7         #region SaveVideoFirstImg 根据视频路径生成视频对应的图片
  8         /// <summary>
  9         /// 根据视频路径生成视频对应的图片
 10         /// </summary>
 11         /// <param name="videoUrl">视频的绝对路径</param>
 12         public static void SaveVideoFirstImg(string videoUrl)
 13         {
 14             var saveFileurl = videoUrl.Substring(0, videoUrl.LastIndexOf(".")) + ".jpg";
 15             Process p = new Process();
 16             p.StartInfo.FileName = string.Format("{0}\ffmpeg.exe", HttpContext.Current.Server.MapPath("~/media/"));
 17             p.StartInfo.CreateNoWindow = true;
 18             p.StartInfo.UseShellExecute = false;
 19             p.StartInfo.Arguments = string.Format("-i {0} -y -f image2 -t 1 {1}", videoUrl, saveFileurl);
 20             p.Start();
 21             p.WaitForExit();
 22             p.Close();
 23             p.Dispose();
 24         }
 25         #endregion
 26 
 27         #region CompressImg 生成缩略图方法
 28         /// <summary>
 29         /// 生成缩略图方法
 30         /// </summary>
 31         /// <param name="oldUrl">完整原始图片路径</param>
 32         /// <param name="newUrl">完整缩略图路径</param>
 33         /// <param name="thumbWidth">缩略图宽度</param>
 34         /// <param name="thumbHeight">缩略图高度</param>
 35         /// <returns>成功生成返回true,失败生成返回false</returns>
 36         public static bool CompressImg(string oldUrl, string newUrl, double thumbWidth, double thumbHeight)
 37         {
 38             if (File.Exists(oldUrl))
 39             {
 40                 //原图加载
 41                 using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(oldUrl))
 42                 {
 43                     var imgFormate = GetImageFormat(sourceImage);
 44 
 45                     //原图宽高均小于模版,不作处理,直接保存
 46                     if (sourceImage.Width <= thumbWidth && sourceImage.Height <= thumbHeight)
 47                     {
 48                         //保存
 49                         sourceImage.Save(newUrl, imgFormate);
 50                     }
 51                     else
 52                     {
 53                         //缩略图宽、高计算
 54                         double newWidth = sourceImage.Width;
 55                         double newHeight = sourceImage.Height;
 56 
 57                         //宽大于高或宽等于高(横图或正方)
 58                         if (sourceImage.Width >= sourceImage.Height) 
 59                         {
 60                             //如果宽大于模版
 61                             if (sourceImage.Width > thumbWidth)
 62                             {
 63                                 //宽按模版,高按比例缩放
 64                                 newWidth = thumbWidth;
 65                                 newHeight = sourceImage.Height * (thumbWidth / sourceImage.Width);
 66                             }
 67                         }
 68                         //高大于宽(竖图)
 69                         else
 70                         {
 71                             //如果高大于模版
 72                             if (sourceImage.Height > thumbHeight)
 73                             {
 74                                 //高按模版,宽按比例缩放
 75                                 newHeight = thumbHeight;
 76                                 newWidth = sourceImage.Width * (thumbHeight / sourceImage.Height);
 77                             }
 78                         }
 79 
 80                         //判断是否为gif或者tiff图片
 81                         if (imgFormate == ImageFormat.Gif || imgFormate == ImageFormat.Tiff)
 82                         {
 83                             //压缩图片
 84                             CompressImgGif(sourceImage, imgFormate, newUrl, (int)newWidth, (int)newHeight);
 85                         }
 86                         else //其它格式图片
 87                         {
 88                             //生成新图,新建一个bmp图片
 89                             System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
 90 
 91                             //新建一个画板
 92                             System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
 93 
 94                             //置背景色
 95                             newG.Clear(Color.Transparent);
 96 
 97                             //设置质量
 98                             newG.InterpolationMode = InterpolationMode.HighQualityBicubic;
 99                             newG.SmoothingMode = SmoothingMode.HighQuality;
100 
101                             //画图
102                             newG.DrawImage(sourceImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, sourceImage.Width, sourceImage.Height), System.Drawing.GraphicsUnit.Pixel);
103 
104                             newImage.Save(newUrl, imgFormate);
105 
106                             //释放资源
107                             newG.Dispose();
108                             newImage.Dispose();
109                         }
110                     }
111                 }
112                 return true;
113             }
114 
115             return false;
116         }
117         #endregion
118 
119         #region CompressImgGif 压缩gif图片
120         /// <summary>
121         /// 压缩gif图片
122         /// </summary>
123         /// <param name="oldUrl"></param>
124         /// <param name="newUrl"></param>
125         /// <param name="thumbWidth"></param>
126         /// <param name="thumbHeight"></param>
127         public static void CompressImgGif(Image sourceImage, ImageFormat format, string newUrl, int width, int height)
128         {
129             //新图第一帧
130             Image new_img = new Bitmap(width, height);
131 
132             //新图其他帧
133             Image new_imgs = new Bitmap(width, height);
134 
135             //新图第一帧GDI+绘图对象
136             Graphics g_new_img = Graphics.FromImage(new_img);
137 
138             //新图其他帧GDI+绘图对象
139             Graphics g_new_imgs = Graphics.FromImage(new_imgs);
140 
141             //配置新图第一帧GDI+绘图对象
142             g_new_img.CompositingMode = CompositingMode.SourceCopy;
143             g_new_img.InterpolationMode = InterpolationMode.HighQualityBicubic;
144             g_new_img.PixelOffsetMode = PixelOffsetMode.HighQuality;
145             g_new_img.SmoothingMode = SmoothingMode.HighQuality;
146             g_new_img.Clear(Color.FromKnownColor(KnownColor.Transparent));
147 
148             //配置其他帧GDI+绘图对象
149             g_new_imgs.CompositingMode = CompositingMode.SourceCopy;
150             g_new_imgs.InterpolationMode = InterpolationMode.HighQualityBicubic;
151             g_new_imgs.PixelOffsetMode = PixelOffsetMode.HighQuality;
152             g_new_imgs.SmoothingMode = SmoothingMode.HighQuality;
153             g_new_imgs.Clear(Color.FromKnownColor(KnownColor.Transparent));
154 
155             //遍历维数
156             foreach (Guid gid in sourceImage.FrameDimensionsList)
157             {
158                 //因为是缩小GIF文件所以这里要设置为Time
159                 //如果是TIFF这里要设置为PAGE
160                 FrameDimension f = format == ImageFormat.Gif ? FrameDimension.Time : FrameDimension.Page;
161 
162                 //获取总帧数
163                 int count = sourceImage.GetFrameCount(f);
164                 //保存标示参数
165                 System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
166                 //
167                 EncoderParameters ep = null;
168 
169                 //每一帧
170                 for (int c = 0; c < count; c++)
171                 {
172                     //选择由维度和索引指定的帧
173                     sourceImage.SelectActiveFrame(f, c);
174                     //第一帧
175                     if (c == 0)
176                     {
177                         //将原图第一帧画给新图第一帧
178                         g_new_img.DrawImage(sourceImage, new Rectangle(0, 0, new_img.Width,new_img.Height), new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), GraphicsUnit.Pixel);
179 
180                         //把振频和透明背景调色板等设置复制给新图第一帧
181                         for (int i = 0; i < sourceImage.PropertyItems.Length; i++)
182                         {
183                             new_img.SetPropertyItem(sourceImage.PropertyItems[i]);
184                         }
185                         ep = new EncoderParameters(1);
186                         //第一帧需要设置为MultiFrame
187                         ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
188 
189                         //保存第一帧
190                         new_img.Save(newUrl, GetCodecInfo(format.Guid), ep);
191                     }
192                     //其他帧
193                     else
194                     {
195                         //把原图的其他帧画给新图的其他帧
196                         g_new_imgs.DrawImage(sourceImage, new Rectangle(0, 0, new_imgs.Width,new_imgs.Height), new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), GraphicsUnit.Pixel);
197 
198                         //把振频和透明背景调色板等设置复制给新图第一帧
199                         for (int i = 0; i < sourceImage.PropertyItems.Length; i++)
200                         {
201                             new_imgs.SetPropertyItem(sourceImage.PropertyItems[i]);
202                         }
203                         ep = new EncoderParameters(1);
204 
205                         //如果是GIF这里设置为FrameDimensionTime
206                         //如果为TIFF则设置为FrameDimensionPage
207                         ep.Param[0] = new EncoderParameter(encoder, (long)(format == ImageFormat.Gif ? EncoderValue.FrameDimensionTime : EncoderValue.FrameDimensionPage));
208 
209                         //向新图添加一帧
210                         new_img.SaveAdd(new_imgs, ep);
211                     }
212                 }
213 
214                 ep = new EncoderParameters(1);
215                 //关闭多帧文件流
216                 ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
217                 new_img.SaveAdd(ep);
218             }
219 
220             //释放文件
221             new_img.Dispose();
222             new_imgs.Dispose();
223             g_new_img.Dispose();
224             g_new_imgs.Dispose();
225         }
226         #endregion
227 
228         #region 压缩文件
229         /// <summary>
230         /// 压缩文件
231         /// </summary>
232         /// <param name="oldImg"></param>
233         /// <param name="newImg"></param>
234         public static void CompressSize(string oldImg, string newImg)
235         {
236 
237             using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(oldImg))
238             {
239                 Bitmap bmp = new Bitmap(sourceImage);
240                 KiSaveAsJPEG(bmp, newImg, 20);
241             }
242 
243         }
244 
245         //// <summary>
246         /// 保存为JPEG格式,支持压缩质量选项
247         /// </summary>
248         /// <param name="bmp"></param>
249         /// <param name="FileName"></param>
250         /// <param name="Qty"></param>
251         /// <returns></returns>
252         public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
253         {
254             try
255             {
256                 EncoderParameter p;
257                 EncoderParameters ps;
258 
259                 ps = new EncoderParameters(1);
260 
261                 p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
262                 ps.Param[0] = p;
263 
264                 bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);
265 
266                 return true;
267             }
268             catch
269             {
270                 return false;
271             }
272         }
273 
274         //// <summary>
275         /// 获取codeinfo
276         /// </summary>
277         /// <param name="mimeType"></param>
278         /// <returns>得到指定mimeType的ImageCodecInfo</returns>
279         private static ImageCodecInfo GetCodecInfo(string mimeType)
280         {
281             ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
282             foreach (ImageCodecInfo ici in CodecInfo)
283             {
284                 if (ici.MimeType == mimeType) return ici;
285             }
286             return null;
287         }
288 
289         /// <summary>
290         /// 获取codeinfo
291         /// </summary>
292         /// <param name="guid"></param>
293         /// <returns></returns>
294         public static ImageCodecInfo GetCodecInfo(Guid guid)
295         {
296             ImageCodecInfo[] icis = ImageCodecInfo.GetImageDecoders();
297 
298             //为 图片编码、解码器 对象 赋值
299             foreach (ImageCodecInfo ici in icis)
300             {
301                 if (ici.FormatID == guid)
302                 {
303                     return ici;
304                 }
305             }
306 
307             return null;
308         }
309         #endregion
310 
311         #region GetImageFormat 获取图片文件格式
312         /// <summary>
313         /// 获取图片文件格式
314         /// </summary>
315         /// <param name="img"></param>
316         /// <returns></returns>
317         public static ImageFormat GetImageFormat(Image img)
318         {
319             if (img != null)
320             {
321                 ImageFormat fileExtension = img.RawFormat,
322                        jpgExtension = ImageFormat.Jpeg,
323                        gifExtension = ImageFormat.Gif,
324                        pngExtension = ImageFormat.Png,
325                        iconExtension = ImageFormat.Icon,
326                        bmpExtension = ImageFormat.Bmp,
327                        tiffExtension = ImageFormat.Tiff,
328                        wmfExtension = ImageFormat.Wmf,
329                        emfExtension = ImageFormat.Emf,
330                        exifExtension = ImageFormat.Exif;
331 
332                 if (fileExtension.Equals(jpgExtension))
333                 {
334                     return ImageFormat.Jpeg;
335                 }
336                 else if (fileExtension.Equals(gifExtension))
337                 {
338                     return ImageFormat.Gif;
339                 }
340                 else if (fileExtension.Equals(pngExtension))
341                 {
342                     return ImageFormat.Png;
343                 }
344                 else if (fileExtension.Equals(iconExtension))
345                 {
346                     return ImageFormat.Icon;
347                 }
348                 else if (fileExtension.Equals(bmpExtension))
349                 {
350                     return ImageFormat.Bmp;
351                 }
352                 else if (fileExtension.Equals(tiffExtension))
353                 {
354                     return ImageFormat.Tiff;
355                 }
356                 else if (fileExtension.Equals(wmfExtension))
357                 {
358                     return ImageFormat.Wmf;
359                 }
360                 else if (fileExtension.Equals(emfExtension))
361                 {
362                     return ImageFormat.Emf;
363                 }
364                 else if (fileExtension.Equals(exifExtension))
365                 {
366                     return ImageFormat.Exif;
367                 }
368             }
369             return ImageFormat.Jpeg;
370         }
371         #endregion
372 
373         #region GetExtension 获得上传文件的扩展名
374         /// <summary>
375         /// 获得上传文件的扩展名
376         /// </summary>
377         /// <param name="img"></param>
378         /// <returns></returns>
379         public static string GetExtension(Image img)
380         {
381             if (img != null)
382             {
383                 ImageFormat fileExtension = img.RawFormat,
384                       jpgExtension = ImageFormat.Jpeg,
385                       gifExtension = ImageFormat.Gif,
386                       pngExtension = ImageFormat.Png,
387                       iconExtension = ImageFormat.Icon,
388                       bmpExtension = ImageFormat.Bmp,
389                       tiffExtension = ImageFormat.Tiff,
390                       wmfExtension = ImageFormat.Wmf,
391                       emfExtension = ImageFormat.Emf,
392                       exifExtension = ImageFormat.Exif;
393 
394                 if (fileExtension.Equals(jpgExtension))
395                 {
396                     return ".jpg";
397                 }
398                 else if (fileExtension.Equals(gifExtension))
399                 {
400                     return ".gif";
401                 }
402                 else if (fileExtension.Equals(pngExtension))
403                 {
404                     return ".png";
405                 }
406                 else if (fileExtension.Equals(iconExtension))
407                 {
408                     return ".icon";
409                 }
410                 else if (fileExtension.Equals(bmpExtension))
411                 {
412                     return ".bmp";
413                 }
414                 else if (fileExtension.Equals(tiffExtension))
415                 {
416                     return ".tiff";
417                 }
418                 else if (fileExtension.Equals(wmfExtension))
419                 {
420                     return ".wmf";
421                 }
422                 else if (fileExtension.Equals(emfExtension))
423                 {
424                     return ".emf";
425                 }
426                 else if (fileExtension.Equals(exifExtension))
427                 {
428                     return ".exif";
429                 }
430             }
431             return ".jpg";
432         }
433         #endregion
434 
435     }
436 
437     #region UploadImageMsg 上传图片后返回上传结果
438     /// <summary>
439     /// 上传图片后返回上传结果
440     /// </summary>
441     public class UploadImageMsg
442     {
443         public UploadImageMsg()
444         {
445             error = 1;
446             url = message = string.Empty;
447         }
448 
449         /// <summary>
450         /// 1错误 0成功
451         /// </summary>
452         public int error { get; set; }
453         /// <summary>
454         /// 错误信息
455         /// </summary>
456         public string message { get; set; }
457         /// <summary>
458         /// 上传成功的url路径
459         /// </summary>
460         public string url { get; set; }
461     }
462     #endregion
View Code
原文地址:https://www.cnblogs.com/maomao999/p/5496946.html