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;
  }

 調用示例

      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));//縮后的小圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM