2011年11月23日 星期三

使用C#實現縮圖功能

當我們的網站有提供使用者上傳圖片時,一般我們只會限制上傳圖檔類型,例如:.jpg、.png、.gif等,或者限制上傳圖檔的大小,至於圖檔的維度我們通常無法限制,原因是在於使用者並不是每個人都有能力針對圖檔進行編輯,所以為了讓使用者上傳的圖檔能符合網站設計,我們可以藉由img標籤裡的屬性width及height來設定,但這種設計的方式會有一個問題,當上傳的圖檔很大時多人同時瀏覽可能會耗費大量網站對外的頻寬影響系統其他使用者,所以比較好的作法是當上傳圖檔時除了原始圖檔外再產生一張縮圖,以下將說明我針對這個需求所撰寫的縮圖程式

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

public class ImageUtility
{
    public ImageUtility()
    {

    }

    public static string ResizeImage(string strFilePath, int longSide)
    {
        float ratio;
        int width;
        int height;
        string suffix = "_s";
        string strDestFilePath;

        if (!File.Exists(strFilePath)) 
        {
            return "";
        }

        if (Path.GetExtension(strFilePath).ToLower() != ".jpg" &&
                Path.GetExtension(strFilePath).ToLower() != ".png" &&
                Path.GetExtension(strFilePath).ToLower() != ".gif") 
        {
            return "";
        }       

        Image img = System.Drawing.Image.FromFile(strFilePath);

        if (!(img.Width > longSide || img.Height > longSide))
        {
            return "";
        }

        if (img.Width > img.Height)
        {
            ratio = (float)longSide / img.Width;
        }
        else 
        {
            ratio = (float)longSide / img.Height;
        }

        width = (int)(img.Width * ratio);
        height = (int)(img.Height * ratio);

        Bitmap bmp = new Bitmap(img, new System.Drawing.Size(width, height));
        strDestFilePath = string.Format(@"{0}\{1}{2}{3}", Path.GetDirectoryName(strFilePath), Path.GetFileNameWithoutExtension(strFilePath), suffix, Path.GetExtension(strFilePath));
        bmp.Save(strDestFilePath);
        
        return strDestFilePath;
    }
}

這個靜態函式是接收原始圖檔目前所在的路徑並產生縮圖,而輸入參數longSide是指縮圖的長邊,舉例來說:如果原始圖檔是維度800X600的圖片,而longSide設定為100的話,那縮圖的維度就是100X75,以下整理函式處理步聚

  1. 檢查原始圖檔是否存在,如果不存在則中止處理。
  2. 檢查原始圖檔是否為.jpg、.png、.gif等格式,如果不是則中止處理。
  3. 當原始圖檔的長寬都小於指定的長度則中止處理。
  4. 以原始圖檔維度中較長的一邊做為縮圖基準,求得縮圖的比率進而得到縮圖後的長寬。
  5. 依得到的長寬產生縮圖,縮圖檔名為:原始檔名_s.副檔名。
上面函式適用於擺放圖檔的父容器是正方形,至於父容器如果是矩形就留待各位看倌思考。

沒有留言:

張貼留言