顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

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.副檔名。
上面函式適用於擺放圖檔的父容器是正方形,至於父容器如果是矩形就留待各位看倌思考。

2009年6月7日 星期日

去除字串最後一個逗號

在一些狀況下,我們可能需要傳送一連串的值給Stored Procedure,所以我們會在程式中串接字串,因為是用for-loop之類的方法,所以字串後面都會多個分隔符號,為了刪除最後一個分隔符號程式設計師大都會用String類別的一些方法去刪除,有些程式設計師會用Substring來處理,在這裡提供比較好的做法。

原本的程式
string mystring = "1,2,3,";
mystring = mystring.Substring(0, mystring.Length-1);

建議
string mystring = "1,2,3,";
mystring = mystring.TrimEnd(new char[]{','});

為什麼說TrimEnd是比較好的做法,因為要用Substring要加更多判斷條件
Substring如果沒有加判斷條件會發生一些狀況
  1. 當mystring = "1"; 時,用Substring則mystring最後值等於"" (理論上是"1");
  2. 當mystring = ""; 時,會發生System.ArgumentOutOfRangeException: 長度不可以小於零。