您现在的位置: 365建站网 > 365文章 > 加水印图片生成缩略图公用函数

加水印图片生成缩略图公用函数

文章来源:365jz.com     点击数:335    更新时间:2009-09-12 17:00   参与评论

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using pic;//加水印图片的命名空间
   
    //参数:上传文件路径
    //返回值:时间+随机数,后缀。格式:“时间|随机数后缀”
    public string Up_load(string file)
    {
        string folder;
        string temp = "";
        DateTime temptime = DateTime.Now;
        folder = temptime.ToString("yyyyMM");
        Random rand = new Random();
        int ran = rand.Next(000, 999);
        string fileName = temptime.ToString("yyyyMMddHHmmss");
        if (FileUpload1.PostedFile.FileName.Trim() != "")//检查上传
        {
            string extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToUpper();
            temp = "" + ran + extension + "";
            string path = HttpContext.Current.Server.MapPath("~") + "//" + "uppic//" + folder;
            if (!Directory.Exists(path))//创建上传路径,如果没有创建
            {
                Directory.CreateDirectory(path);
            }
            path = path + "//" + fileName + extension;
                FileUpload1.PostedFile.SaveAs(path);//保存文件

                System.Drawing.Image image = System.Drawing.Image.FromFile(path);//获得上传图片的宽和高
                int width = image.Width;
                int height = image.Height;
                double ratio = (double)width / (double)height;//得到图片宽和高的比例

                if (ratio >= 2.0f || ratio <= 0.5f)//检测图片宽高比例,不符合要求的禁止上传,并删除图片
                {
                    Response.Write("<script language=javascript>alert('您上传的图片不符合要求,请重新上传!');

                                                 history.back();</script>");
                    image.Dispose();
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    Response.End();
                }
                else//符合上传要求的
                {
                    ToThumbnailImages("/" + folder + "/" + fileName + extension, fileName + temp, 700, folder);//固定图片宽高
                    string tpath = HttpContext.Current.Server.MapPath("~") + "//" + "uppic//" + folder;
                    tpath = tpath + "//" + fileName + temp;

                    pic.ImageModification wm = new ImageModification();//给图片加水印
                    wm.DrawedImagePath = Server.MapPath("") + "/Image/" + "a.gif";
                    wm.ModifyImagePath = tpath;
                    wm.RightSpace = 300;
                    wm.BottoamSpace = 255;
                    wm.LucencyPercent = 80;
                    wm.OutPath = tpath;
                    wm.DrawImage();

                    mFileName = fileName + temp;
                    image.Dispose();

                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    //设置图片尺寸
                    int bw = 0, mw = 0, sw = 0;
                    string[] tempw = ConfigurationManager.AppSettings["B_Pic"].ToString().Split('*');
                    bw = Convert.ToInt16(tempw[0].ToString());
                    tempw = ConfigurationManager.AppSettings["M_Pic"].ToString().Split('*');
                    mw = Convert.ToInt16(tempw[0].ToString());
                    tempw = ConfigurationManager.AppSettings["S_Pic"].ToString().Split('*');
                    sw = Convert.ToInt16(tempw[0].ToString());
                    //按指定尺寸生成缩略图
                    ToThumbnailImages("/" + folder + "/" + fileName + temp, "b_" + fileName + temp, bw, folder);
                    ToThumbnailImages("/" + folder + "/" + fileName + temp, "m_" + fileName + temp, mw, folder);
                    ToThumbnailImages("/" + folder + "/" + fileName + temp, "s_" + fileName + temp, sw, folder);

                    if (File.Exists(tpath))
                    {
                        File.Delete(tpath);
                    }
                }
                return temptime + "|" + ran + extension + "";
            }
        else
        {
            return temptime + "|";
        }
    }

#region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
        #region htmimes[".jpe"]="image/jpeg";//允许缩略的图片类型
        htmimes[".jpeg"] = "image/jpeg";
        htmimes[".jpg"] = "image/jpeg";
        htmimes[".png"] = "image/png";
        htmimes[".tif"] = "image/tiff";
        htmimes[".tiff"] = "image/tiff";
        htmimes[".bmp"] = "image/bmp";
        #endregion
    }
    #endregion

    #region Helper

    /// <summary>
    /// 获取图像编码解码器的所有相关信息
    /// </summary>
    /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
    /// <returns>返回图像编码解码器的所有相关信息</returns>
    static ImageCodecInfo GetCodecInfo(string mimeType)
    {
        ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo ici in CodecInfo)
        {
            if (ici.MimeType == mimeType) return ici;
        }
        return null;
    }

    /// <summary>
    /// 检测扩展名的有效性
    /// </summary>
    /// <param name="sExt">文件名扩展名</param>
    /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
    bool CheckValidExt(string sExt)
    {
        bool flag = false;
        string[] aExt = AllowExt.Split('|');
        foreach (string filetype in aExt)
        {
            if (filetype.ToLower() == sExt)
            {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /// <summary>
    /// 保存图片
    /// </summary>
    /// <param name="image">Image 对象</param>
    /// <param name="savePath">保存路径</param>
    /// <param name="ici">指定格式的编解码参数</param>
    void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)
    {
        //设置 原图片 对象的 EncoderParameters 对象
        EncoderParameters parameters = new EncoderParameters(1);
        parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)90));
        image.Save(savePath, ici, parameters);
        parameters.Dispose();
    }
    #endregion

    #region Methods

    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="sourceImagePath">原图片路径(相对路径)</param>
    /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
    /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>
    public void ToThumbnailImages(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, string folder)
    {
        string SourceImagePath = sourceImagePath;
        string ThumbnailImagePath = thumbnailImagePath;
        int ThumbnailImageWidth = thumbnailImageWidth;
        string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();
        if (SourceImagePath.ToString() == System.String.Empty) throw new NullReferenceException("SourceImagePath is null!");
        if (!CheckValidExt(sExt))
        {
            throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]", "SourceImagePath");
        }
        //从 原图片 创建 Image 对象
        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~") + "//uppic//" + SourceImagePath);
        int num = ((ThumbnailImageWidth / 4) * 3);
        int width = image.Width;
        int height = image.Height;
        //计算图片的比例
        if ((((double)width) / ((double)height)) >= 1.3333333333333333f)
        {
            num = ((height * ThumbnailImageWidth) / width);
        }
        else
        {
            ThumbnailImageWidth = ((width * num) / height);
        }
        if ((ThumbnailImageWidth < 1) || (num < 1))
        {
            return;
        }
        //用指定的大小和格式初始化 Bitmap 类的新实例
        Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);
        //从指定的 Image 对象创建新 Graphics 对象
        Graphics graphics = Graphics.FromImage(bitmap);
        //清除整个绘图面并以透明背景色填充
        graphics.Clear(Color.Transparent);
        //在指定位置并且按指定大小绘制 原图片 对象
        graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
        image.Dispose();
        try
        {
            //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
            string savepath = (ThumbnailImagePath == null ? SourceImagePath : ThumbnailImagePath);
            string sp1 = HttpContext.Current.Server.MapPath("~\\uppic\\" + folder + "\\" + savepath);
            SaveImage(bitmap, sp1, GetCodecInfo((string)htmimes[sExt]));
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            bitmap.Dispose();
            graphics.Dispose();
        }
    }
    #endregion

--------------------------------加图片水印类文件---------------------------

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;//用到的名称空间
namespace picmark
{
 /// <summary>
 ///图片修改类,主要是用来保护图片版权
 /// </summary>
 public class ImageModification
 {
  #region "member fields"
  private string modifyImagePath=null;
  private string drawedImagePath=null;
  private int rightSpace;
  private int bottoamSpace;
  private int lucencyPercent=70;
  private string outPath=null;
  #endregion
  public ImageModification()
  {
  }
  #region "propertys"
  /// <summary>
  /// 获取或设置要修改的图像路径
  /// </summary>
  public string ModifyImagePath
  {
   get{return this.modifyImagePath;}
   set{this.modifyImagePath=value;}
  }
  /// <summary>
  /// 获取或设置在画的图片路径(水印图片)
  /// </summary>
  public string DrawedImagePath
  {
   get{return this.drawedImagePath;}
   set{this.drawedImagePath=value;}
  }
  /// <summary>
  /// 获取或设置水印在修改图片中的右边距
  /// </summary>
  public int RightSpace
  {
   get{return this.rightSpace;}
   set{this.rightSpace=value;}
  }
  //获取或设置水印在修改图片中距底部的高度
  public int BottoamSpace
  {
   get{return this.bottoamSpace;}
   set{this.bottoamSpace=value;}
  }
  /// <summary>
  /// 获取或设置要绘制水印的透明度,注意是原来图片透明度的百分比
  /// </summary>
  public int LucencyPercent
  {
   get{return this.lucencyPercent;}
   set
   {
    if(value>=0&&value<=100)
     this.lucencyPercent=value;
   }
  }
  /// <summary>
  /// 获取或设置要输出图像的路径
  /// </summary>
  public string OutPath
  {
   get{return this.outPath;}
   set{this.outPath=value;}
  }
  #endregion
  #region "methods"
  /// <summary>
  /// 开始绘制水印
  /// </summary>
  public void DrawImage()
  {
   Image modifyImage=null;
   Image drawedImage=null;
   Graphics g=null;
   try
   {
    //建立图形对象
    modifyImage=Image.FromFile(this.ModifyImagePath);
    drawedImage=Image.FromFile(this.DrawedImagePath);
    g=Graphics.FromImage(modifyImage);
    //获取要绘制图形坐标
    int x=modifyImage.Width-this.rightSpace;
    int y=modifyImage.Height-this.BottoamSpace;
    //设置颜色矩阵
    float[][] matrixItems ={
             new float[] {1, 0, 0, 0, 0},
             new float[] {0, 1, 0, 0, 0},
             new float[] {0, 0, 1, 0, 0},
             new float[] {0, 0, 0, (float)this.LucencyPercent/100f, 0},
             new float[] {0, 0, 0, 0, 1}};

    ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
    ImageAttributes imgAttr=new ImageAttributes();
    imgAttr.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);
    //绘制阴影图像
    g.DrawImage(
     drawedImage,
     new Rectangle(x,y,drawedImage.Width,drawedImage.Height),
     0,0,drawedImage.Width,drawedImage.Height,
     GraphicsUnit.Pixel,imgAttr);
    //保存文件
    string[] allowImageType={".jpg",".gif",".png",".bmp",".tiff",".wmf",".ico"};
    FileInfo file=new FileInfo(this.ModifyImagePath);
    ImageFormat imageType=ImageFormat.Gif;
    switch(file.Extension.ToLower())
    {
     case ".jpg":
      imageType=ImageFormat.Jpeg;
      break;
     case ".gif":
      imageType=ImageFormat.Gif;
      break;
     case ".png":
      imageType=ImageFormat.Png;
      break;
     case ".bmp":
      imageType=ImageFormat.Bmp;
      break;
     case ".tif":
      imageType=ImageFormat.Tiff;
      break;
     case ".wmf":
      imageType=ImageFormat.Wmf;
      break;
     case ".ico":
      imageType=ImageFormat.Icon;
      break;
     default:
      break;
    }
    MemoryStream ms=new MemoryStream();
    modifyImage.Save(ms,imageType);
    byte[] imgData=ms.ToArray();
    modifyImage.Dispose();
    drawedImage.Dispose();
    g.Dispose();
    FileStream fs=null;
    if(this.OutPath==null || this.OutPath=="")
    {
     File.Delete(this.ModifyImagePath);
     fs=new FileStream(this.ModifyImagePath,FileMode.Create,FileAccess.Write);
    }
    else
    {
     fs=new FileStream(this.OutPath,FileMode.Create,FileAccess.Write);
    }
    if(fs!=null)
    {
     fs.Write(imgData,0,imgData.Length);
     fs.Close();
    }
   }
   finally
   {
    try
    {
     drawedImage.Dispose();
     modifyImage.Dispose();
     g.Dispose();
    }
    catch{;}
   }
  }
  #endregion
 }
}

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (335人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号