ASP.NET Image uploading with Resizing

前端 未结 14 1868
广开言路
广开言路 2020-11-30 01:27

I have an aspx page which will upload images to server harddisk from client pc

But now i need to change my program in such a way that it would allow me to resize the

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 01:46

    private void ResizeImage(FileUpload fileUpload)
    {
        // First we check to see if the user has selected a file
        if (fileUpload.HasFile)
        {
            // Find the fileUpload control
            string filename = fileUpload.FileName;
    
            // Check if the directory we want the image uploaded to actually exists or not
            if (!Directory.Exists(MapPath(@"Uploaded-Files")))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(MapPath(@"Uploaded-Files"));
            }
            // Specify the upload directory
            string directory = Server.MapPath(@"Uploaded-Files\");
    
            // Create a bitmap of the content of the fileUpload control in memory
            Bitmap originalBMP = new Bitmap(fileUpload.FileContent);
    
            // Calculate the new image dimensions
            int origWidth = originalBMP.Width;
            int origHeight = originalBMP.Height;
            int sngRatio = origWidth / origHeight;
            int newWidth = 100;
            int newHeight = newWidth / sngRatio;
    
            // Create a new bitmap which will hold the previous resized bitmap
            Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
    
            // Create a graphic based on the new bitmap
            Graphics oGraphics = Graphics.FromImage(newBMP);
            // Set the properties for the new graphic file
            oGraphics.SmoothingMode = SmoothingMode.AntiAlias; 
            oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
            // Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
            // Save the new graphic file to the server
            newBMP.Save(directory + "tn_" + filename);
    
            // Once finished with the bitmap objects, we deallocate them.
            originalBMP.Dispose();
            newBMP.Dispose();
            oGraphics.Dispose();
    
            // Write a message to inform the user all is OK
            label.Text = "File Name: " + filename + "
    "; label.Text += "Content Type: " + fileUpload.PostedFile.ContentType + "
    "; label.Text += "File Size: " + fileUpload.PostedFile.ContentLength.ToString() + ""; // Display the image to the user Image1.Visible = true; Image1.ImageUrl = @"Uploaded-Files/tn_" + filename; } else { label.Text = "No file uploaded!"; } }

提交回复
热议问题