2014-02-21

[T4] url, base64, sprite 三種格式的 icons.css 產生器

之前有寫過 [PHP] url, base64, sprite 三種格式的 icons.css 產生器,這次換用 C# T4 Text Templates 來製作這個功能:

int spriteGap = 30;  
var scanTypes = new string[]{".jpg", ".gif", ".png"};

string workDirectory = 
    Path.GetDirectoryName(this.Host.TemplateFile);


/* 取得圖檔資訊 */  
List<ImageInfo> imageList = Directory
    .EnumerateFiles(Path.Combine(workDirectory, "icons"))
    .Where(path => scanTypes.Contains(Path.GetExtension(path)))
    .Select(path => 
    {
        var image = Image.FromFile(path);

        return new ImageInfo{
            FilePath = path,
            FileName = Path.GetFileName(path),
            IconImage = image,
            IconName = Path.GetFileNameWithoutExtension(path),
            TopOffset = 0,
            Width = image.Width,
            Height = image.Height,
            IsAnimated = ImageAnimator.CanAnimate(image),
        };
    })
    .OrderBy(info => info.IsAnimated)
    .ToList();



/*檢查重複的圖檔名稱*/
List<string> repeatList = imageList.GroupBy(info => info.IconName)
    .Where(g => g.Count() > 1)
    .SelectMany(g => g.Select(x => x.FileName))
    .ToList();

if(repeatList.Count > 0){
    throw new Exception(
        "出現重複的圖檔名稱[" + String.Join(", ", repeatList) + "]"
    );
}   



/* 製作 CSS Sprite */
int sumHeight = imageList.Sum( info => info.Height);
int spriteWidth = imageList.Max( info => info.Width);
int spriteHeight = sumHeight + (imageList.Count - 1) * spriteGap;

var bitmap = new Bitmap(spriteWidth, spriteHeight);

using (Graphics graphics = Graphics.FromImage(bitmap))
{           
    int nextTop = 0;
    for(int i=0; i< imageList.Count; i++){
        /*忽略具有動畫的 GIF 圖片*/ 
        if(imageList[i].IsAnimated){ continue; } 

        imageList[i].TopOffset = nextTop;
        
        graphics.DrawImage(imageList[i].IconImage, 0, nextTop);
            
        nextTop = nextTop + imageList[i].Height + spriteGap;
    }
        
    graphics.Save();
}

SaveOutput("icons.sprite.png"); 
bitmap.Save(
    Path.Combine(workDirectory, "icons.sprite.png"), 
    ImageFormat.Png
);
bitmap.Dispose();

下載完整程式: t4_make_icons_css.zip

沒有留言:

張貼留言

你好!歡迎你在我的 Blog 上留下你寶貴的意見。