ASP.NET Загрузка изображений с изменением размера - PullRequest
34 голосов
/ 31 октября 2008

У меня есть страница aspx, которая будет загружать изображения на жесткий диск сервера с клиентского ПК

Но теперь мне нужно изменить свою программу таким образом, чтобы она позволила мне изменить размер изображения при загрузке.

У кого-нибудь есть идеи по этому поводу? Я не смог найти такие свойства / методы с управлением сервером файлов ввода

Есть ли кто-нибудь, чтобы вести меня?

Ответы [ 14 ]

14 голосов
/ 31 октября 2008

После сохранения файла на сервере вы можете использовать такой код для изменения размера. Этот код позаботится о соотношении длина / ширина при изменении размера.

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;
}
5 голосов
/ 16 февраля 2014

Как изменить размер и загрузить изображение только для расширений .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;
            }
        }

И событие Button1_Click

        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
                }
            }
        }

Спасибо ...

5 голосов
/ 31 октября 2008

Вы не сможете изменить размер «на лету», поскольку вам потребуется полное изображение, прежде чем выполнять какие-либо преобразования изображения. Однако после завершения загрузки и до того, как вы отобразите какие-либо результаты для своего пользователя, вы можете использовать этот основной метод изменения размера изображения, который я использовал в нескольких моих приложениях:

   ''' <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
4 голосов
/ 23 февраля 2010

Другой подход - позволить пользователю настроить размер в браузере, а затем изменить размер изображения, как описано в других ответах.

Итак, взгляните на это решение, которое позволяет загружать и обрезать изображения с помощью jQuery, jCrop & ASP.NET .

3 голосов
/ 17 августа 2012

Это то, как я делал в своем проекте, исходя из вашего состояния (высота / ширина) вы можете изменить параметр, т. Е. (MaxHeight)

Статья в блоге: Как изменить размер изображения при загрузке в asp.net с помощью c #

 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 голосов
/ 06 ноября 2008

Вам понадобится использовать класс WebClient для загрузки удаленного образа.

После этого вы можете изменить его размер ... Используйте DrawImage, а не GetThumbnailImage. Убедитесь, что вы утилизируете свои растровые и графические маркеры .. (используйте с помощью {}). Установите все настройки качества на высокий.

Возможно, вы захотите сначала взглянуть на исходный код моего популярного средства изменения размера изображения ... Это поможет вам избежать некоторых типичных проблем.

1 голос
/ 22 февраля 2010

Вы можете использовать это, это делает для меня отличную работу. Но он плохо обрабатывает изображения с низким разрешением. К счастью, я использую многие из них. Просто отправьте ему изображение 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 голос
/ 26 февраля 2009

Чтобы изменить размер изображения и получить меньшие размеры, просто внесите следующие изменения

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

     Graphics g = Graphics.FromImage(bmpOut);

как указано выше, установите для imagem значение Format24bppRgb PixelFormat.

и когда вы сохраняете файл, вы также устанавливаете ImageFormat. Как это:

bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);
1 голос
/ 06 февраля 2009
//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 
0 голосов
/ 09 октября 2015
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; }
...