利用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)

原图:


缩略图


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