水印圖片

 public class CoverHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
        public CoverHandler() { }
        //水印圖片路徑
        private const string WATERMARK_URL = "~/images/button_nouse.gif";
        //默認圖片路徑
        private const string DEFAULTIMAGE_URL = "~/images/books_01.gif";
        public void ProcessRequest(HttpContext context)
        {
            //設置保存圖片的類型
            context.Response.ContentType = "image/jpeg";
            //加載圖片的路徑
            string path = context.Request.MapPath(DEFAULTIMAGE_URL);
            //context.Request.PhysicalPath 爲images/BookCovers下的圖片
            if (File.Exists(context.Request.PhysicalPath))
            {
                //配置中存在路徑就覆蓋默認路徑
                path = context.Request.PhysicalPath;
            }
            //加載圖片路徑
            using (Image Cover = Image.FromFile(path))
            {
                //加載水印圖片路徑
                using (Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL)))
                {
                   
                    if (path!=DEFAULTIMAGE_URL)
                    {
                        //實例化一個畫布
                        using (Graphics g = Graphics.FromImage(Cover))
                        {
                            //添加水印到圖片上
                            g.DrawImage(watermark, new Rectangle(Cover.Width- watermark.Width, Cover.Height- watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
                        }
                    }
                   
                }
                //保存當前畫布
                Cover.Save(context.Response.OutputStream,ImageFormat.Jpeg);
                //結束
                context.Response.End();
            }
        }
    }
相關文章
相關標籤/搜索