C#圖片壓縮

功能函數,從項目中剝離而來函數

/// <summary>
  /// 圖片壓縮功能
  /// </summary>
  /// <param name="sourceImage">原圖</param>
  /// <param name="targetSize">目標壓縮尺寸</param>
  /// <returns></returns>
  public static Image imgCompress(Image sourceImage, Size targetSize)  ///圖片壓縮功能
  {
    int targetWidth = targetSize.Width, targetHeight = targetSize.Height;  //圖片轉換的目標的尺寸;因爲圖片原有的比例問題,目標尺寸不等於最終的尺寸。
    int width;//圖片最終的寬
    int height;//圖片最終的高
    try
    {
      System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
      Bitmap targetPicture = new Bitmap(targetWidth, targetHeight);
      Graphics g = Graphics.FromImage(targetPicture);
      g.Clear(Color.White);
      //計算縮放圖片的大小
      if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
      {
        width = targetWidth;
        height = (width * sourceImage.Height) / sourceImage.Width;
      }
      else if (sourceImage.Width <= targetWidth && sourceImage.Height >  targetHeight)
      {
        height = targetHeight;
        width = (height * sourceImage.Width) / sourceImage.Height;
      }
      else if (sourceImage.Width <= targetWidth && sourceImage.Height <=  targetHeight)
      {
        width = sourceImage.Width;
        height = sourceImage.Height;
      }
      else
      {
        width = targetWidth;
        height = (width * sourceImage.Height) / sourceImage.Width;
        if (height > targetHeight)
        {
          height = targetHeight;
          width = (height * sourceImage.Width) / sourceImage.Height;
        }
      }
      g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) /  2, width, height);
      sourceImage.Dispose();
      return targetPicture;
    }
    catch (Exception ex)
    {
    }
    return null;
  }

 調用示例spa

      HttpPostedFile pic_upload = Request.Files["file"];
      System.Drawing.Image bigImage = clsPublic.imgCompress(System.Drawing.Image.FromStream(pic_upload.InputStream), new Size(400, 400));//縮後的大圖
      System.Drawing.Image minImage =clsPublic.imgCompress(System.Drawing.Image.FromStream(pic_upload.InputStream), new Size(50, 50));//縮後的小圖
相關文章
相關標籤/搜索