在保存到服务器之前,使用IMAGERESIZER获得较小的图像 [英] using IMAGERESIZER for smaller images, before saving to the server

查看:101
本文介绍了在保存到服务器之前,使用IMAGERESIZER获得较小的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在保存图像之前使用Imageresizer调整了成像器的大小.
但是,如果我保存个人资料图像,然后查看保存图像的文件夹,那么我看到仍然会保存原始图像,而不是较小的图像.

我这样尝试:

Hi everybody,

I am using Imageresizer to resize the imagers before saving the images.
But if I save an profile image, and I look in the folder where the images are saved, then I see that still the original images are saved and not the smaller ones.

I try it like this:

[HttpPost]
       public ActionResult EditPhotos(UserProfile user, HttpPostedFileBase file)
       {
           // string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more...
           bool isSavedSuccessfully = true;
           try
           {


           if (file != null || file.ContentLength > 0)
           {

               if (IsImage(file) == false)
               {
                   // Invalid file type
                   return Json(new { Message = "Error in saving file, Go back and  try again" });
               }
               int iFileSize = file.ContentLength;
               if (iFileSize > 3048576)  // 1MB
               {
                   // File exceeds the file maximum size
                   return Json(new { Message = "Image is to large , Go back and  try again" });
               }


               //ModelState.AddModelError("file", "This field is requird");
           }

           if (ModelState.IsValid)
           {
               var job = new ImageJob(file, "~/Images/profile/<guid>", new Instructions("mode=max;format=jpg;width=400;height=400;"));
               job.CreateParentDirectory = true;
               job.AddFileExtension = true;
               job.Build();

               var DirSeparator = Path.DirectorySeparatorChar;

               var fileName = Path.GetFileName(job.FinalPath);
               var path = Path.Combine(Server.MapPath(@"\\Images\\profile" + @"\" + fileName.Replace('+', '_')));

               file.SaveAs(path);



               //string username = User.Identity.Name;
               if (ModelState.IsValid)
               {
                   string username = User.Identity.Name;
                   // Get the userprofile
                   user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
                   user.Image = new byte[file.ContentLength];
                   file.InputStream.Read(user.Image, 0, file.ContentLength);


               }

               // Update fields
               user.ImageMimeType = file.ContentType;
               db.Entry(user).State = EntityState.Modified;
               db.SaveChanges();



           }
          }
           catch (Exception ex)
           {
               isSavedSuccessfully = false;

           }

           if (isSavedSuccessfully)
           {
               return Redirect(Url.Action("Edit", "Account") + "#tabs-2");
           }
           else
           {
               return Json(new { Message = "Error in saving file, Go back and  try again" });
           }

       }




这就是我使用Imageresizer的地方:




and this is where I use the Imageresizer:

var job = new ImageJob(file, "~/Images/profile/<guid>", new Instructions("mode=max;format=jpg;width=400;height=400;"));
               job.CreateParentDirectory = true;
               job.AddFileExtension = true;
               job.Build();


谢谢

推荐答案

byte[] data = (byte[])dsGetIdentityCard.Tables[0].Rows[i]["Photo"];
           dr["Photo"] = CreateThumbnail(data, 200);







//Function to Resize Photo
    // Takes 2 Arguments :
    //    1. Image as byte[]
    //    2. Maximum height of the Image in pixels
    public static byte[] CreateThumbnail(byte[] PassedImage, int LargestSide)
    {
        byte[] ReturnedThumbnail;

        using (MemoryStream StartMemoryStream = new MemoryStream(),
                            NewMemoryStream = new MemoryStream())
        {
            // write the string to the stream  
            StartMemoryStream.Write(PassedImage, 0, PassedImage.Length);

            // create the start Bitmap from the MemoryStream that contains the image  
            Bitmap startBitmap = new Bitmap(StartMemoryStream);

            // set thumbnail height and width proportional to the original image.  
            int newHeight;
            int newWidth;
            double HW_ratio;
            if (startBitmap.Height > startBitmap.Width)
            {
                newHeight = LargestSide;
                HW_ratio = (double)((double)LargestSide / (double)startBitmap.Height);
                newWidth = (int)(HW_ratio * (double)startBitmap.Width);
            }
            else
            {
                newWidth = LargestSide;
                HW_ratio = (double)((double)LargestSide / (double)startBitmap.Width);
                newHeight = (int)(HW_ratio * (double)startBitmap.Height);
            }

            // create a new Bitmap with dimensions for the thumbnail.  
            Bitmap newBitmap = new Bitmap(newWidth, newHeight);

            // Copy the image from the START Bitmap into the NEW Bitmap.  
            // This will create a thumnail size of the same image.  
            newBitmap = ResizeImage(startBitmap, newWidth, newHeight);

            // Save this image to the specified stream in the specified format.  
            newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

            // Fill the byte[] for the thumbnail from the new MemoryStream.  
            ReturnedThumbnail = NewMemoryStream.ToArray();
        }

        // return the resized image as a string of bytes.  
        return ReturnedThumbnail;
    }

    // Resize a Bitmap  
    private static Bitmap ResizeImage(Bitmap image, int width, int height)
    {
        Bitmap resizedImage = new Bitmap(width, height);
        using (Graphics gfx = Graphics.FromImage(resizedImage))
        {
            gfx.DrawImage(image, new Rectangle(0, 0, width, height),
                new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
        }
        return resizedImage;
    }


这篇关于在保存到服务器之前,使用IMAGERESIZER获得较小的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆