Asp.Net upload images and generate high-definition thumbnails

Keywords: Programming Google

In asp.net, the function of uploading pictures or commonly used, generating thumbnails is also commonly used. There are many ways to use baidu or google, c ා, but when I use it, I find that the thumbnail is not clear, the thumbnail picture is too large, and so on. Here is the code I'm dealing with on the picture. The effect is good, so I'll share it with you. (the effect can achieve the effect of some drawing software.)

The code is as follows:

/// <summary>
    ///asp.net upload picture and generate thumbnail
    /// </summary>
    ///< param name = "upimage" > htmlinputfile control < / param >
    ///The saved paths are the folders under the relative server paths < / param >
    ///< param name = "sthumbextension" > thumb of thumbnail < / param >
    ///< param name = "intthumbwidth" > width of generated thumbnail < / param >
    ///< param name = "intthumbheight" > height of thumbnail generated < / param >
    ///< returns > thumbnail name < / returns >
    public string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)
    {
        string sThumbFile = "";
        string sFilename = "";        
        if (upImage.PostedFile != null)
        {
            HttpPostedFile myFile = upImage.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
                return "No image upload selected";            
            //Get the extension of the upImage selection file
            string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
            //Determine whether it is a picture format
            if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
                return "Incorrect picture format";
            
            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);
            sFilename = System.IO.Path.GetFileName(myFile.FileName);
            int file_append = 0;
            //Check whether there is a picture with the same name in the current folder. If there is one, it will be in the file name + 1
            while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                    + file_append.ToString() + extendName;
            }
            System.IO.FileStream newFile
                = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename),
                System.IO.FileMode.Create, System.IO.FileAccess.Write);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();
            //The above is the original picture uploaded
            try
            {
                //Artwork loading
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
                {
                    //Original width and height
                    int width = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;
                    //Get the size of the first drawing (compare the width of the original / the width of the thumbnail and the height of the original / the height of the thumbnail)
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    //Determine whether the thumbnail exists with the same name file under the current folder
                    file_append = 0;
                    sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;
                    while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                    {
                        file_append++;
                        sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                            file_append.ToString() + extendName;
                    }
                    //Absolute path to thumbnail save
                    string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
                    //Create a new drawing board to draw the original drawing with the minimum equal scale compression size
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //Draw the middle picture
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //HD, smooth
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                            sourceImage,
                            new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                            new System.Drawing.Rectangle(0, 0, width, height),
                            System.Drawing.GraphicsUnit.Pixel
                            );
                        }
                        //Create a new board to draw the middle map at the size of thumbnail
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                      //Draw thumbnails http://www.cnblogs.com/sosoft/
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //HD, smooth
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                    }
                }
            }
            catch
            {
                //Delete on error
                System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));
                return "Incorrect picture format";
            }
            //Back to thumbnail name
            return sThumbFile;
        }
        return "No pictures selected";
    }

HtmlInputFile control I think everyone should know that input type=file

Let's put the calling code together with C

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>Picture upload</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>        
        <input id="File1" runat="server" type="file" /></div><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </form>
</body>
</html>

Simple call

protected void Button1_Click(object sender, EventArgs e)
 {
         string a = this.UpLoadImage(this.File1, "UpLoad/", "thumb_", 118, 118);  
 }

 

In this way, there will be two more pictures in your UpLoad folder, one is the original picture and the other is the thumbnail.

 

 

Provide a better algorithm, because there is no time to test and debug, for reference only

That is, when the first step is to reduce the scale equally, it can be divided into several times, that is, to reduce the original map to the middle map of the above code by a percentage,

For example: the original picture is 500 * 500. I want to abbreviate it to 100 * 80. The code program above will first draw a middle picture of 100 * 100, and then draw 100 * 80 on this picture,

Before drawing the 100 * 100 middle map, if you first draw the 300 * 300 middle map, then draw the 100 * 100 on the basis of 300 * 300, and then draw the 100 * 80, it will be better than the code effect above. The picture is clearer, that is, the more the middle map, the better the effect. You can try it.

Development technology article: http://www.cnblogs.com/sosoft/p/kaifajishu.html

Posted by dxdolar on Fri, 10 Jan 2020 00:58:27 -0800