ASP.NET 图片上传及大小调整

35

我有一个aspx页面,它可以从客户端pc上传图像到服务器硬盘

但现在我需要改变我的程序,使其允许我在上传时调整图像大小。

有谁有任何想法吗?我在Input文件服务器控件中找不到这样的属性/方法。

有人能指导我吗?


2
你如何从“服务器”上传到“客户端”? - ine
4
我建议使用免费且开源的库@.NET中的图像大小调整在一行代码中完成此操作。其他答案(目前)可能存在一个或多个常见陷阱 - Lilith River
ImageBuilder.Current.Build(HttpPostedFile f, string destinationFilename, new ResizeSettings("maxwidth=200&maxheight=200")); 可以将上传的图片文件按照指定的最大宽度和最大高度进行调整,并保存到指定的目标文件名中。 - Lilith River
1
这是一个使用jCrop的例子,结合ImageResizing.Net库进行服务器端图像调整。 - Lilith River
我感觉“计算机语言学家”在.Net中与图像调整有所涉及。 - Lloyd Powell
是的,那是我,作者。很抱歉忘记了[完整披露]标签,通常我不会这样做。 - Lilith River
14个回答

16

一旦文件保存到服务器上,您可以使用以下代码进行调整大小。该代码将在调整大小时处理长度/宽度比。

public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{

    System.Drawing.Bitmap bmpOut = null;

    try
    {
        Bitmap loBMP = new Bitmap(lcFilename);
        ImageFormat loFormat = loBMP.RawFormat;

        decimal lnRatio;
        int lnNewWidth = 0;
        int lnNewHeight = 0;

        if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
            return loBMP;

        if (loBMP.Width > loBMP.Height)
        {
            lnRatio = (decimal)lnWidth / loBMP.Width;
            lnNewWidth = lnWidth;
            decimal lnTemp = loBMP.Height * lnRatio;
            lnNewHeight = (int)lnTemp;
        }
        else
        {
            lnRatio = (decimal)lnHeight / loBMP.Height;
            lnNewHeight = lnHeight;
            decimal lnTemp = loBMP.Width * lnRatio;
            lnNewWidth = (int)lnTemp;
        }


        bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
        g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

        loBMP.Dispose();
    }
    catch
    {
        return null;
    }
    return bmpOut;
}

这与问题有点偏离,但是这种方法如何处理低分辨率图像?我总是得到我的图像出现畸形的情况。 - Tim Meers
我通常会通过那段代码传输高分辨率的图片,所以我无法给你一个好的答案。但是,将其与应用程序连接并进行测试实际上非常容易,因此您可以尝试一下,我认为这不会花费您太多时间。 - JPrescottSanders
除非在DrawImage调用期间使用ImageAttributes实例中的TileModeXY,否则您将在图像的外边框上获得50%的白色(或黑色)线。 - Lilith River
请参见 https://dev59.com/u1nUa4cB1Zd3GeqPb5cb。 - Lilith River

5

由于在执行任何图像转换之前,您需要拥有完整的图像,因此您将无法“即时”调整大小。但是,在上传完成并在向用户显示任何结果之前,您可以使用我现在在我的几个应用程序中使用的基本图像调整大小方法:

   ''' <summary>
   '''    Resize image with GDI+ so that image is nice and clear with required size.
   ''' </summary>
   ''' <param name="SourceImage">Image to resize</param>
   ''' <param name="NewHeight">New height to resize to.</param>
   ''' <param name="NewWidth">New width to resize to.</param>
   ''' <returns>Image object resized to new dimensions.</returns>
   ''' <remarks></remarks>
   Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image

      Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)

      If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
         Throw New NotSupportedException("Pixel format of the image is not supported.")
      End If

      Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)

      graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
      graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
      graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)
      graphicsImage.Dispose()
      Return bitmap

   End Function

+1 指出图像调整必须在整个图像上传完成后进行。 - quakkels

4
如何调整大小并仅上传 .jpg 扩展名的图像:
在 upload.aspx 页面。
    <asp:FileUpload ID="ProductImage" runat="server"/>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
 <asp:TextBox runat="server" ID="txtProductName" CssClass="form-control" />
                        <asp:RequiredFieldValidator runat="server" ControlToValidate="txtProductName" ErrorMessage="The Product name field is required." />

同时上传及裁剪图片 (upload.aspx.cs)
缩放

/// <summary>
/// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://onlineshoping.somee.com/
/// Complete This Page Coding On January 05, 2014
/// Programing C# By Visual Studio 2013 For Web
/// Dot Net Version 4.5
/// Database Virsion MSSQL Server 2005
/// </summary>
        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;
            }
        }

按钮1的点击事件

        string filePath = "~\\Image\\";//your normal image path
        if (Page.IsValid)
        {
            HttpPostedFile myFile = ProductImage.PostedFile;//Get Slected Image
            int nFileLen = myFile.ContentLength;//Get slected Image Size
            string myimag = txtProductName.Text;//Get user input image name
            Guid ImageName = Guid.NewGuid();//get unique id
            if ((myFile != null) && (nFileLen > 1048576))
            {
                LabelAddStatus.Text = "minimum size exceed"; //If file image size 1 MB above
            }
            else
            {
                try
                {
                    if (ProductImage.HasFile)
                    {
                        String fileExtension = System.IO.Path.GetExtension(ProductImage.FileName).ToLower();
                        String[] allowedExtensions = { ".jpg" };//Declare For Allowed Extension
                        for (int i = 0; i < allowedExtensions.Length; i++)
                        {
                            if (fileExtension == allowedExtensions[i])
                            {
                                // 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);
                                bool success = ResizeImageAndUpload(newFile, filePath + ("thumbs"+myimag + ImageName), 100, 100);//Save image your thumb image path
                                success = ResizeImageAndUpload(newFile, filePath + (myimag + ImageName), 768, 1024);//Save image your normal image path
                                //delete the temp file.
                                newFile.Close();
                                System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
                                LabelAddStatus.Text = "File uploaded.";
                            }
                            else
                            {
                                LabelAddStatus.Text = "Unable to accept file type..";
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    //No Exception Message
                }
            }
        }

感谢您的...


4

4
这是我在项目中的做法,根据你的条件 (高度/宽度),你可以更改参数,比如(MaxHeight)。
 public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
        {
            var ratio = (double)maxHeight / image.Height;
    
            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);
    
            var newImage = new Bitmap(newWidth, newHeight);
            using (var g = Graphics.FromImage(newImage))
            {
                g.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }

点击按钮时:

protected void Button1_Click(object sender, EventArgs e)
{
  lblmsg.Text="";
  if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
  {
    Guid uid = Guid.NewGuid();
    string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
    string SaveLocation = Server.MapPath("LogoImagesFolder") + "\\" + uid+fn;
    try
    {
      string fileExtention = File1.PostedFile.ContentType;
      int fileLenght = File1.PostedFile.ContentLength;
      if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
      {
        if (fileLenght <= 1048576)
        {
          System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
          System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
          objImage.Save(SaveLocation,ImageFormat.Png);
          lblmsg.Text = "The file has been uploaded.";
          lblmsg.Style.Add("Color", "Green");
         }
         else 
         {
           lblmsg.Text = "Image size cannot be more then 1 MB.";
           lblmsg.Style.Add("Color", "Red");
          }
       }
     else {
             lblmsg.Text = "Invaild Format!";
             lblmsg.Style.Add("Color", "Red");
           }
     }
     catch (Exception ex)
       {
          lblmsg.Text= "Error: " + ex.Message;
          lblmsg.Style.Add("Color", "Red");
       }
   }
 }

2
您需要使用WebClient类来下载远程图像。
之后,您可以调整其大小...使用DrawImage而不是GetThumbnailImage。确保处理位图和图形句柄(使用using{})。将所有质量设置为高。
您可能想先查看我流行的图像调整大小的源代码...它将帮助您避免一些常见的问题区域。

1

你可以使用这个,它对我来说做得很好。但是对于低分辨率的图像,它处理得不太好。幸运的是,我没有使用太多这样的图像。只需将图像byte[]和期望的输出发送给它,你就可以开始了。

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) 
{ 
    using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) 
    { 
        Size newSize = CalculateDimensions(oldImage.Size, targetSize); 

        using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) 
        { 
            newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution); 
            using (Graphics canvas = Graphics.FromImage(newImage)) 
            { 
                canvas.SmoothingMode = SmoothingMode.AntiAlias; 
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
                canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; 
                canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize)); 
                MemoryStream m = new MemoryStream(); 
                newImage.Save(m, ImageFormat.Jpeg); 
                return m.GetBuffer(); 
            } 
        } 

    } 
} 

private static Size CalculateDimensions(Size oldSize, int targetSize) 
{ 
    Size newSize = new Size(); 
    if (oldSize.Width > oldSize.Height) 
    { 
        newSize.Width = targetSize; 
        newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width); 
    } 
    else 
    { 
        newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height); 
        newSize.Height = targetSize; 
    } 
    return newSize; 
} 

1
//Here is another WAY fox!!! i have actually modify the code from You all. HIHI
//First, add one textBox and one FileUpload Control, and a button

//paste this in your code behind file... after public partial class admin : System.Web.UI.Page

    string OriPath;
    string ImageName;

public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
    {
        Size NewSize;
        double tempval;

        if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
        {
            if (OriginalHeight > OriginalWidth)
                tempval = FormatSize / Convert.ToDouble(OriginalHeight);
            else
                tempval = FormatSize / Convert.ToDouble(OriginalWidth);

            NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
        }
        else
            NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
    } 



//Now, On Button click add the folwing code.

if (FileUpload1.PostedFile != null)
        {
           ImageName = TextBox1.Text+".jpg";


           OriPath = Server.MapPath("pix\\") + ImageName;

           //Gets the Full Path using Filecontrol1 which points to actual location in the hardisk :)

           using (System.Drawing.Image Img = System.Drawing.Image.FromFile(System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName)))
           {
               Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 800);

               using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
               {
                   ImgThnail.Save(OriPath, Img.RawFormat);
                   ImgThnail.Dispose();
               }
               Img.Dispose();
           }
}


//Enjoy. If any problem,, mail me at izacmail@gmail.com 

1

要调整图像大小并获得较小的尺寸,只需进行以下更改

    bmpOut = new Bitmap(lnNewWidth, lnNewHeight, **System.Drawing.Imaging.PixelFormat.Format24bppRgb**);

     Graphics g = Graphics.FromImage(bmpOut);

当你设置图像的PixelFormat时,将其设置为Format24bppRgb。

当你保存文件时,也要设置ImageFormat。就像这样:

bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);

0
public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)
    {
        System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);
 double widthRatio = (double)fullSizeImg.Width / (double)Width;
  double heightRatio = (double)fullSizeImg.Height / (double)Height;
  double ratio = Math.Max(widthRatio, heightRatio);
 int newWidth = (int)(fullSizeImg.Width / ratio);
 int newHeight = (int)(fullSizeImg.Height / ratio);
        //System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
 //DateTime MyDate = DateTime.Now;
 //String MyString = MyDate.ToString("ddMMyyhhmmss") + imageUrl.Substring(imageUrl.LastIndexOf("."));
 thumbNailImg.Save(destPath, ImageFormat.Jpeg);
 thumbNailImg.Dispose();
        return "";
    }
    public bool ThumbnailCallback() { return false; }

欢迎来到stackoverflow,并感谢您抽出时间来回答问题。同时考虑添加一些解释。 - Olivier De Meulder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接