利用ImageResizer類庫開發.NET版本的timthumb.php

    /// <summary>
    /// 生成縮略圖
    /// 參數說明
    /// src:圖片路徑,如:~/Uploads/xxx.jpg 或者 http://www.xxx.jpg
    /// w:圖片寬度
    /// p:圖片高度
    /// mode:生成模式,分Max, Pad, Crop, Carve 和 Stretch,默認Crop
    /// 備註:需要在建立timthumb-cache,並賦予可寫權限,否則會報錯
    /// </summary>
    public class timthumb : IHttpHandler
    {
        private static Object thisLock = new Object();
        public void ProcessRequest(HttpContext context)
        {
            var src = context.Request.QueryString["src"];
            int w = 0, h = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["w"]))
            {
                int.TryParse(context.Request.QueryString["w"], out w);
            }
            if (w > 3200)
                w = 0;
            if (!string.IsNullOrEmpty(context.Request.QueryString["h"]))
            {
                int.TryParse(context.Request.QueryString["h"], out h);
            }
            if (h > 3200)
                h = 0;
            var cacheDir = "~/timthumb-cache/";
            var http = src.ToLower().StartsWith("http://") || src.ToLower().StartsWith("https://");
            var extension = Path.GetExtension(src);
            var thumbnail = string.Empty;
            var orginal = string.Empty;
            if (http)
            {
                //將源文件緩存起來
                var uri = new Uri(src);
                orginal = cacheDir + "remote" + uri.ToString().Replace(uri.Scheme, null).Replace(":/", null);
                thumbnail = string.Format("{0}.{1}_{2}{3}", orginal, w, h, extension);
            }
            else
            {
                if (!src.StartsWith("~/"))
                {
                    if (src.StartsWith("/"))
                    {
                        orginal = "~" + src;
                        thumbnail = string.Format("{0}{1}.{2}_{3}{4}", cacheDir, src.Substring(1, src.Length - 1), w, h, extension);
                    }
                    else
                    {
                        orginal = "~/" + src;
                        thumbnail = string.Format("{0}{1}.{2}_{3}{4}", cacheDir, src, w, h, extension);
                    }
                }
                else
                {
                    orginal = src;
                    thumbnail = string.Format("{0}{1}.{2}_{3}{4}", cacheDir, src.Substring(2, src.Length - 2), w, h, extension);
                }
            }
            if (!File.Exists(context.Server.MapPath(thumbnail)))
            {
                lock (thisLock)
                {
                    if (!File.Exists(context.Server.MapPath(thumbnail)))
                    {
                        if (http)
                        {
                            if (!File.Exists(context.Server.MapPath(orginal)))
                            {
                                var fileInfo = new FileInfo(context.Server.MapPath(orginal));
                                if (!fileInfo.Directory.Exists)
                                {
                                    fileInfo.Directory.Create();
                                }
                                using (var wc = new WebClient())
                                {
                                    wc.DownloadFile(src, context.Server.MapPath(orginal));
                                }
                            }
                        }
                        else if (!File.Exists(context.Server.MapPath(orginal)))
                        {
                            throw new Exception(context.Server.MapPath(orginal) + "不存在");
                        }
                        var thumbnailInfo = new FileInfo(context.Server.MapPath(thumbnail));
                        if (!thumbnailInfo.Directory.Exists)
                        {
                            thumbnailInfo.Directory.Create();
                        }
                        ImageBuilder.Current.Build(context.Server.MapPath(orginal), thumbnailInfo.FullName,
                            new ResizeSettings(string.Format("format={3}&mode={2}{0}{1}"
                                , (w == 0 ? null : "&width=" + w.ToString())
                                , (h == 0 ? null : "&height=" + h.ToString())
                                , string.IsNullOrEmpty(context.Request.QueryString["mode"]) ? "Crop" : context.Request.QueryString["mode"]
                                , extension.Substring(1, extension.Length - 1))));
                    }
                }
            }
            context.Response.Redirect(thumbnail);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

timthumb.php ,是php生成縮略圖的腳本,wordpress有使用到它。ImageResizer類庫提供了各種生成縮略圖的功能,使用ImageResizer很方便的生成縮略圖。注意免費版是有限制的。

在Global.asax和httpModules(iis7則使用modules)上使用以上代碼均可實現縮略圖的功能,但是移植性比較差,需要修改源碼或者配置web.config。使用一般性處理程序(IHttpHandler)編譯後,直接上傳到服務器即可使用,使用方式類似timthumb.php。

~/timthumb.ashx?src=~/uploads/1.jpg&w=100&h=100

配合URL重定向即可使用類似如下格式的縮略圖路徑:

/Uploads/703a2487-6dbd-4534-969d-e32916c0f716.jpg_Thumbnail_196_99999.jpg

演示網站見這裏:http://www.thisis10.com 拾圖網,下載:http://www.thisis10.com/timthumb.zip (67.2KB)

原圖:


縮略圖


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章