图片的按比例缩小.

来源:互联网 发布:淘宝关注人数最多的店 编辑:程序博客网 时间:2024/05/01 12:40
  1. public static byte[] ResizeImageFile(byte[] imageFile, int targetSizeW, int targetSizeH)
  2.     {
  3.         System.Drawing.Image original = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
  4.         int targetH, targetW;
  5.         targetW = targetSizeW;
  6.         targetH = (int)(original.Height * ((float)targetSizeW / (float)original.Width));
  7.         if (targetH > targetSizeH)
  8.         {
  9.             targetH = targetSizeH;
  10.             targetW = (int)(original.Width * ((float)targetSizeH / (float)original.Height));
  11.         }
  12.         if (targetSizeW < (int)original.Width || targetSizeH < (int)original.Height)
  13.         {
  14.             System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(new MemoryStream(imageFile));
  15.             // Create a new blank canvas.  The resized image will be drawn on this canvas.
  16.             Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
  17.             bmPhoto.SetResolution(72, 72);
  18.             Graphics grPhoto = Graphics.FromImage(bmPhoto);
  19.             grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
  20.             grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
  21.             grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
  22.             grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
  23.             // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
  24.             MemoryStream mm = new MemoryStream();
  25.             bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
  26.             original.Dispose();
  27.             imgPhoto.Dispose();
  28.             bmPhoto.Dispose();
  29.             grPhoto.Dispose();
  30.             return mm.GetBuffer();
  31.         }
  32.         else
  33.         {
  34.             return imageFile;
  35.         }
  36.     }
 
原创粉丝点击