随笔 - 750  文章 - 1  评论 - 107  阅读 - 34万

[转][C#]图片上添加水印、缩略图

直接上代码:

复制代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.IO;

public partial class upfile : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileContentType = FileUpload1.PostedFile.ContentType;
        if (fileContentType == "image/gif")
        {
            upgif();
        }
        else
        {
            upother();
        }
    }

    void upother()
    {
        if (FileUpload1.HasFile)
        {
            string fileContentType = FileUpload1.PostedFile.ContentType;
            if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
            {
                string name = FileUpload1.PostedFile.FileName;                  // 客户端文件路径

                FileInfo file = new FileInfo(name);
                string fileName = file.Name;                                    // 文件名称
                string fileName_s = "s_" + file.Name;                           // 缩略图文件名称
                string fileName_sy = "text_" + file.Name;                         // 水印图文件名称(文字)
                string fileName_syp = "water_" + file.Name;                       // 水印图文件名称(图片)
                string webFilePath = Server.MapPath("upfile/y/" + fileName);        // 服务器端文件路径
                string webFilePath_s = Server.MapPath("upfile/s/" + fileName_s);  // 服务器端缩略图路径
                string webFilePath_sy = Server.MapPath("upfile/sy/" + fileName_sy); // 服务器端带水印图路径(文字)
                string webFilePath_syp = Server.MapPath("upfile/syp/" + fileName_syp); // 服务器端带水印图路径(图片)
                string webFilePath_sypf = Server.MapPath("watermark.gif"); // 服务器端水印图路径(图片)

                try
                {
                    FileUpload1.SaveAs(webFilePath);                                // 使用 SaveAs 方法保存文件
                    AddWater(webFilePath, webFilePath_sy);
                    AddWaterPic(webFilePath, webFilePath_syp, webFilePath_sypf);
                    MakeThumbnail(webFilePath, webFilePath_s, 200, 150, "Cut");     // 生成缩略图方法  Image1.ImageUrl = "upfile/y/" + fileName;
                    Image1.ImageUrl = "upfile/y/" + fileName;
                    Image2.ImageUrl = "upfile/s/" + fileName_s;
                    Image3.ImageUrl = "upfile/sy/" + fileName_sy;
                    Image4.ImageUrl = "upfile/syp/" + fileName_syp;
                    ImgUrl.Text = Image2.ImageUrl;
                }
                catch (Exception ex)
                {
                    Label1.Text = "提示:文件上传失败,失败原因:" + ex.Message;
                }
            }
            else
            {
                Label1.Text = "提示:文件类型不符";
            }
        }
    }


    void upgif()
    {
        if (FileUpload1.HasFile)
        {
            string name = FileUpload1.PostedFile.FileName;

            FileInfo file = new FileInfo(name);
            string fileName = file.Name;
            string webFilePath = Server.MapPath("upfile/y/" + fileName);
            if (!File.Exists(webFilePath))
            {
                try
                {
                    FileUpload1.SaveAs(webFilePath);
                    Image1.ImageUrl = "upfile/y/" + fileName;
                    ImgUrl.Text = Image2.ImageUrl;
                }
                catch (Exception ex)
                {
                    Label1.Text = "提示:文件上传失败,失败原因:" + ex.Message;
                }
            }
            else
            {
                Label1.Text = "提示:文件已经存在,请重命名后上传";
            }

        }
        else
        {
            Label1.Text = "提示:文件类型不符";
        }
    }

    /**/
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径(物理路径)</param>
    /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>    
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW"://指定高宽缩放(可能变形)                
                break;
            case "W"://指定宽,高按比例                    
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H"://指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut"://指定高宽裁减(不变形)                
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }

    /**/
    /// <summary>
    /// 在图片上增加文字水印
    /// </summary>
    /// <param name="Path">原服务器图片路径</param>
    /// <param name="Path_sy">生成的带文字水印的图片路径</param>
    protected void AddWater(string Path, string Path_sy)
    {
        string addText = "test.com";
        System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
        g.DrawImage(image, 0, 0, image.Width, image.Height);
        System.Drawing.Font f = new System.Drawing.Font("Verdana", 60);
        System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Green);

        g.DrawString(addText, f, b, 35, 35);
        g.Dispose();

        image.Save(Path_sy);
        image.Dispose();
    }

    /**/
    /// <summary>
    /// 在图片上生成图片水印
    /// </summary>
    /// <param name="Path">原服务器图片路径</param>
    /// <param name="Path_syp">生成的带图片水印的图片路径</param>
    /// <param name="Path_sypf">水印图片路径</param>
    protected void AddWaterPic(string Path, string Path_syp, string Path_sypf)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
        g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
        g.Dispose();

        image.Save(Path_syp);
        image.Dispose();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Image1.Attributes.Add("onclick", "rem(this.src)");
        Image2.Attributes.Add("onclick", "rem(this.src)");
        Image3.Attributes.Add("onclick", "rem(this.src)");
        Image4.Attributes.Add("onclick", "rem(this.src)");
    }
}
复制代码

 

posted on   z5337  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2018-04-25 [Html] jQuery Grid
2016-04-25 [html]CSS 小贴士
2016-04-25 [经验]PLSQL乱码解决
2014-04-25 C# 读写 ini 配置文件
2014-04-25 [转]VB 读写ini 配置文件
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示