1. 程式人生 > >【C#】Web上傳圖片並加上水印

【C#】Web上傳圖片並加上水印

前言

我們經常在網上下載圖片,有很多圖片都是有水印的,就搞的很煩。今天分享一個如何給自己上傳到自己網址上的圖片加上水印。

需求

在自己網站上傳一張圖片,儲存在Upload資料夾中並且有自己的水印,只能上傳圖片,其他的檔案上傳均無效。
我們可以在前端限制一下上傳檔案的格式,當然這隻能矇混小菜,大佬可以在網頁的開發者工具中把你的限制改掉。我們還要在後端限制一下(畢竟能力有限)。

需求實現

前端可以用jquery技術實現

    <script>
        $(function () {
            $(":file").change(function () {
                var fileNmae = $(this).val();
                var ext = fileNmae.substring(fileNmae.lastIndexOf('.'));
                if (ext == ".jpg" || ext == ".png"||ext==".gif") {
                    return true;
                } else {
                    $(this).val = "";
                }
            });
        });
    </script>

後端程式碼

            context.Response.ContentType = "text/html";

            //拿到上傳來的檔案
            HttpPostedFile file = context.Request.Files["imgFile"];

            if (file == null)
            {
                context.Response.End();
            }

            //後臺校驗
            string ext = Path.GetExtension(file.FileName);
            if (!(ext == ".jpg" || ext == ".png" || ext == ".gif"))
            {
                context.Response.Write("格式有誤");
            }
            else
            {
                string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
                file.SaveAs(context.Request.MapPath(path));

                string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>", path);
                //把圖片顯示給使用者
                context.Response.Write(str);
            }

新增水印

前面我們現實了一個上傳圖片的功能,當然格式不是就那三個,可以自己在擴充套件,然後開始新增水印,前端的程式碼不用變,後端我們用Graphics類下的DrawString方法在我們上傳的圖片上繪製水印。

            context.Response.ContentType = "text/html";

            //拿到上傳來的檔案
            HttpPostedFile file = context.Request.Files["imgFile"];

            if (file == null)
            {
                context.Response.End();
            }

            //把上傳的檔案做成一個Image物件
            Image image = Image.FromStream(file.InputStream);

            Graphics graphics = Graphics.FromImage(image);
            string str = "版權所有:閆偉強";
            graphics.DrawString(str, new Font("黑體", 16), new SolidBrush(Color.Black), new PointF
                                (image.Width - (25 * str.Length), image.Height - 22));
            string strPath = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;

            image.Save(context.Request.MapPath(strPath), ImageFormat.Jpeg);

            string strHtml = string.Format("<html><head></head><body><img src='{0}'/></body></html>", strPath);

            context.Response.Write(strHtml);

效果
在這裡插入圖片描述

總結

   學習就是一個反覆的過程,慢慢積累,既然學過了,就要留下來點!