当前位置: 代码迷 >> ASP.NET >> .net给网站图片加水印后,只有指定路径图片可以显示,其他图片出有关问题,帮帮忙
  详细解决方案

.net给网站图片加水印后,只有指定路径图片可以显示,其他图片出有关问题,帮帮忙

热度:1176   发布时间:2013-02-25 00:00:00.0
.net给网站图片加水印后,只有指定路径图片可以显示,其他图片出问题,帮帮忙
.net给网站图片加水印后(同时网站做了伪静态处理),只有指定路径图片可以显示,其他图片出问题,大虾帮帮忙 !
源文件如下:
web.Config中
httpModules>
<add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter"/>
</httpModules>
<httpHandlers>
<add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
<add verb="*" path="*" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
<add verb="*" path="*.shtml" type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>

<add verb="*" path="admin/editor/attached/image/*/*.jpg" type="CoverHandler"/>
</httpHandlers>
在App_Code文件夹中的CoverHandler.cs代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

/// <summary>
/// CoverHandler 的摘要说明
/// </summary>
public class CoverHandler :IHttpHandler
{
  //水印图片路径
  private const string WATERMARK_URL = "~/admin/images/1381686.gif";

  //默认图片路径
  private const string DEFAULTIMAGE_URL = "~/admin/Images/default.jpg";
  public CoverHandler()
  {
   
  }
  public void ProcessRequest(HttpContext context) {
  System.Drawing.Image Cover;
  //判断请求的物理路径中,是否存在文件。
  if (File.Exists(context.Request.PhysicalPath))
  {
  //加载文件
  Cover = System.Drawing.Image.FromFile(context.Request.PhysicalPath);

  //加载水印图片
  System.Drawing.Image watermark = System.Drawing.Image.FromFile(context.Request.MapPath(WATERMARK_URL));

  //实例化画布
  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);

  //释放画布
  g.Dispose();

  //释放水印图片
  watermark.Dispose();
  }
  else { 
   
  //加载默认图片
  Cover = System.Drawing.Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
  }

  //设置输出格式
  context.Request.ContentType = "image/jpeg";

  //将图片存入输出流
  Cover.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

  Cover.Dispose();
  context.Response.End();
  }

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

------解决方案--------------------------------------------------------
/// <summary>
/// 转换带有索引像素格式的图像
/// </summary>
/// <param name="imgPathOriginal"></param>
/// <param name="imgNew"></param>
/// <param name="g"></param>
private static void GetUsableImg(string imgPathOriginal, out System.Drawing.Image imgNew, out System.Drawing.Graphics g)
{
System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(imgPathOriginal);
  相关解决方案