65.9K
CodeProject 正在变化。 阅读更多。
Home

上传时调整图像大小的函数

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (7投票s)

2007年10月21日

CPOL

2分钟阅读

viewsIcon

58622

downloadIcon

1512

这是一个快速的 C# 函数,可以根据最大宽度和最大高度参数按比例调整 JPG 的大小。

Screenshot - imgup.jpg
我的应用中该功能的截图。

引言

我编写了一个快速的 C# 函数,用于在 ASP.NET 中使用,它接受 ImageUpload 控件的名称、保存路径以及最大高度和最大宽度参数。然后,它保存图像(仅 JPG)文件,如果无错误则返回 true,否则返回 false

结果发现它不像看起来那么简单。通过 FileUpload 引用时,我遇到了奇怪的清理错误和文件无法正确关闭的问题。调试帮助我意识到你不能两次“使用”同一个 FileUpload 控件。因此,我修改了代码。

背景

大多数文章似乎都是从有人在网上搜索解决方案开始的,然后解决方案并不完全有效,所以他们使其有效并在此处添加。这也不例外。

我自学了 Visual Basic .NET 6 个月,目前正在学习 C# 3 周。所以我的 C# 代码可能不够简洁……但我会努力。错误处理并不完美,但它能完成任务。

Using the Code

我已经更新了代码并提供了完整版本。它采用 Web 控件的形式,并使用查询字符串来保持值的唯一性。确保你的文件夹对 ASPNET 帐户和 SYSTEM(我想是这两个……不太确定)具有写入权限。将控件拖放到你的 ASP.NET 页面中。

我的代码使用 DropDownBox 来选择不同的文件名进行上传。你可以删除它。我 99% 确定我已经正确地释放并关闭了所有打开的流和变量。

这是完整的代码隐藏文件

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class admin_Uploader2 : System.Web.UI.UserControl
{
    public bool ResizeImageAndUpload(System.IO.FileStream newFile, 
	string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)
    {        
        try
        {
            // Declare variable for the conversion
            float ratio;   

            // Create variable to hold the image
            System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);

            // Get height and width of current image
            int width = (int)thisImage.Width;
            int height = (int)thisImage.Height;

            // Ratio and conversion for new size
            if (width > maxWidth)
            {
                ratio = (float)width / (float)maxWidth;
                width = (int)(width / ratio);
                height = (int)(height / ratio);
            }

            // Ratio and conversion for new size
            if (height > maxHeight)
            {
                ratio = (float)height / (float)maxHeight;
                height = (int)(height / ratio);
                width = (int)(width / ratio);
            }

            // Create "blank" image for drawing new image
            Bitmap outImage = new Bitmap(width, height);
            Graphics outGraphics = Graphics.FromImage(outImage);
            SolidBrush sb = new SolidBrush(System.Drawing.Color.White);

            // Fill "blank" with new sized image
            outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);
            outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
            sb.Dispose();
            outGraphics.Dispose();
            thisImage.Dispose();

            // Save new image as jpg
            outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + ".jpg"), 
			System.Drawing.Imaging.ImageFormat.Jpeg);
            outImage.Dispose();

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        //Path to store uploaded files on server - make sure your paths are unique
        string Id = Request.QueryString["id"];
        string filePath = "~\\Image_Upload\\" + Id + "-" + 
			DropDownListImage.SelectedValue.ToString();
        string thumbPath = "~\\Image_Upload\\" + Id + "-" + 
		DropDownListImage.SelectedValue.ToString() + "_thumb";        
        
        // Check that there is a file
        if (fileUploader.PostedFile != null)
        {
            // Check file size (mustn't be 0)
            HttpPostedFile myFile = fileUploader.PostedFile;
            int nFileLen = myFile.ContentLength;
            if ((nFileLen > 0) && 
		(System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg"))
            {
                // Read file into a data stream
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                myFile.InputStream.Dispose();
                
                // Save the stream to disk as temporary file. 
	       // make sure the path is unique!
                System.IO.FileStream newFile
                        = new System.IO.FileStream
			(Server.MapPath(filePath + "_temp.jpg"),
                            		    System.IO.FileMode.Create);
                newFile.Write(myData, 0, myData.Length);
                
                // run ALL the image optimisations you want here..... 
	       // make sure your paths are unique
                // you can use these booleans later 
	       // if you need the results for your own labels or so.
                // don't call the function after the file has been closed.
                bool success = ResizeImageAndUpload(newFile, thumbPath, 100, 100);
                success = ResizeImageAndUpload(newFile, filePath, 768, 1024);

                // tidy up and delete the temp file.
                newFile.Close();            
  
                // don't delete if you want to keep original files on server 
	       // (in this example its for a real estate website
                // the company might want the large originals 
	       // for a printing module later.
                System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
            }          
        } 
    }    
} 

不确定你是否需要所有这些……?而且我觉得我的边距都乱了。

关注点

我想有一种方法可以在不保存临时文件然后删除它的情况下完成此操作……但这最简单。它也可以扩展为 GIF 和 PNG 文件类型。但我的应用程序只需要 JPG。

我基本上是从另外两个示例中重写了这段代码

历史

  • 2007 年 10 月 21 日:初始发布
© . All rights reserved.