asp. net upload image and handle watermark and thumbnail example code

  • 2020-06-15 08:00:06
  • OfStack

Methods:


upFileClass.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;
/// <summary>
/// upFileClass  Summary description of 
/// </summary>
public class upFileClass
{
    public upFileClass()
    {
        //
        // TODO:  Add constructor logic here 
        //
    }
    /// <summary>
    ///  Generate thumbnails 
    /// </summary>
    /// <param name="originalImagePath"> Source map path (physical path) </param>
    /// <param name="thumbnailPath"> Thumbnail path (physical path) </param>
    /// <param name="width"> Thumbnail width </param>
    /// <param name="height"> Thumbnail height </param>
    /// <param name="mode"> How to generate thumbnails </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":// Specify height and width scaling (possible distortion) 
                break;
            case "W":// Specify width and height to scale 
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H":// Specify height and width in proportion 
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut":// Specified height and width cut (without deformation) 
                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;
        }
        // new 1 a bmp The picture 
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
        // new 1 A drawing board 
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
        // Set up a high quality interpolation 
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        // Set high quality , Low speed presents smoothness 
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        // Empty the canvas and fill it with a transparent background color 
        g.Clear(System.Drawing.Color.Transparent);
        // Draws the specified part of the original image at the specified location and at the specified size 
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
        new System.Drawing.Rectangle(x, y, ow, oh),
        System.Drawing.GraphicsUnit.Pixel);
        try
        {
            // In order to jpg Format to save thumbnails 
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
    /// <summary>
    ///  Add a text watermark to an image 
    /// </summary>
    /// <param name="Path"> Path to the original server image </param>
    /// <param name="Path_sy"> The generated image path with text watermark </param>
    public static void AddShuiYinWord(string Path, string Path_sy)
    {
        string addText = " Love wisdom from ";
        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", 16);
        System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);
        g.DrawString(addText, f, b, 15, 15);
        g.Dispose();
        image.Save(Path_sy);
        image.Dispose();
    }
    /// <summary>
    ///  Generate image watermark on the image 
    /// </summary>
    /// <param name="Path"> Path to the original server image </param>
    /// <param name="Path_syp"> The generated image path with image watermark </param>
    /// <param name="Path_sypf"> Watermark image path </param>
    public static void AddShuiYinPic(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();
    }
}
 

Default. aspx code:
 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>asp.net  Upload pictures and process them   The watermark   The thumbnail </title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <asp:FileUpload ID="FileUpload1" runat="server" BorderColor="Gray" BorderWidth="1px" />
        <asp:Button ID="Button1" runat="server" onClick="Button1_Click" Text=" upload " BorderColor="Gray" BorderWidth="1px" Width="70px" /><br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
   </div>
    </form>
</body>
</html>
 

Default. aspx. cs code:

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.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileContentType = FileUpload1.PostedFile.ContentType;
            if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
            {
                string name = FileUpload1.PostedFile.FileName; //  Client file path 
                FileInfo file = new FileInfo(name);
                string fileName = file.Name; //  The file name 
                string fileName_s = "s_" + file.Name; //  Thumbnail file name 
                string fileName_sy = "sy_" + file.Name; //  Name of watermark File (text) 
                string fileName_syp = "syp_" + file.Name; //  Name of watermark File (image) 
                // The following paths can be modified as appropriate 
                string webFilePath = Server.MapPath("file/" + fileName); //  Server side file path 
                string webFilePath_s = Server.MapPath("file/" + fileName_s);  //  Server side thumbnail path 
                string webFilePath_sy = Server.MapPath("file/" + fileName_sy); //  Server side with watermark path ( The text )
                string webFilePath_syp = Server.MapPath("file/" + fileName_syp); //  Server side with watermark path ( The picture )
                // The following is the path of the watermark image 1 Make sure you're ready 1 A watermark image! 
                string webFilePath_sypf = Server.MapPath("file/shuiyin.jpg"); //  Server side watermark path ( The picture )
                if (!File.Exists(webFilePath))
                {
                    try
                    {
                        FileUpload1.SaveAs(webFilePath); //  use  SaveAs  Method save file 
                        upFileClass.AddShuiYinWord(webFilePath, webFilePath_sy);
                        upFileClass.AddShuiYinPic(webFilePath, webFilePath_syp, webFilePath_sypf);
                        upFileClass.MakeThumbnail(webFilePath, webFilePath_s, 130, 130, "Cut"); //  Method of generating thumbnails 
                        Label1.Text = " Tip: File" " + fileName + " "Upload successfully and generate" " + fileName_s + " "Thumbnail, file type: " + FileUpload1.PostedFile.ContentType + " , the file size is: " + FileUpload1.PostedFile.ContentLength + "B";
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = " Note: File upload failed. Reason for failure: " + ex.Message;
                    }
                }
                else
                {
                    Label1.Text = " Tip: The file already exists. Please rename and upload ";
                }
            }
            else
            {
                Label1.Text = " Note: File type does not match ";
            }
        }
    }
}


Related articles: