调整图像大小而不会丢失质量MVC 4

问题描述 投票:-1回答:3

我只是想重新调整图像尺寸而不会失去质量我可以使用它吗?

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
   WebImage img = new WebImage(file.InputStream);
   if (img.Width > 1000)
   img.Resize(1000, 1000);
   img.Save("path");
   return View();
}

或WebImage调整大小但丢失图像质量?谢谢

asp.net .net asp.net-mvc asp.net-mvc-4 c#-4.0
3个回答
6
投票

这是我使用的代码。在你的行动中调用ResizeImage方法。

public class Size
{
    public Size(int width, int height)
    {
        Width = width;
        Height = height;
    }
    public int Width { get; set; }
    public int Height { get; set; }
}

public static bool ResizeImage(string orgFile, string resizedFile, ImageFormat format, int width, int height)
{
    try
    {
        using (Image img = Image.FromFile(orgFile))
        {
            Image thumbNail = new Bitmap(width, height, img.PixelFormat);
            Graphics g = Graphics.FromImage(thumbNail);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.DrawImage(img, rect);
            thumbNail.Save(resizedFile, format);
        }

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

2
投票

取自http://www.codeproject.com/Tips/481015/Rename-Resize-Upload-Image-ASP-NET-MVC

首先要创建一个图像保存类(我只是复制和粘贴)

public class ImageResult
{
public bool Success { get; set; }
public string ImageName { get; set; }
public string ErrorMessage { get; set; }
}

然后你需要另一个类保存方法(我只需要复制和粘贴)

 public class ImageUpload
{
    // set default size here
    public int Width { get; set; }

    public int Height { get; set; }

    // folder for the upload, you can put this in the web.config
    private readonly string UploadPath = "~/Images/Items/";

    public ImageResult RenameUploadFile(HttpPostedFileBase file, Int32 counter = 0)
    {
        var fileName = Path.GetFileName(file.FileName);

        string prepend = "item_";
        string finalFileName = prepend + ((counter).ToString()) + "_" + fileName;
        if (System.IO.File.Exists
            (HttpContext.Current.Request.MapPath(UploadPath + finalFileName)))
        {
            //file exists => add country try again
            return RenameUploadFile(file, ++counter);
        }
        //file doesn't exist, upload item but validate first
        return UploadFile(file, finalFileName);
    }

    private ImageResult UploadFile(HttpPostedFileBase file, string fileName)
    {
        ImageResult imageResult = new ImageResult { Success = true, ErrorMessage = null };

        var path =
      Path.Combine(HttpContext.Current.Request.MapPath(UploadPath), fileName);
        string extension = Path.GetExtension(file.FileName);

        //make sure the file is valid
        if (!ValidateExtension(extension))
        {
            imageResult.Success = false;
            imageResult.ErrorMessage = "Invalid Extension";
            return imageResult;
        }

        try
        {
            file.SaveAs(path);

            Image imgOriginal = Image.FromFile(path);

            //pass in whatever value you want
            Image imgActual = Scale(imgOriginal);
            imgOriginal.Dispose();
            imgActual.Save(path);
            imgActual.Dispose();

            imageResult.ImageName = fileName;

            return imageResult;
        }
        catch (Exception ex)
        {
            // you might NOT want to show the exception error for the user
            // this is generally logging or testing

            imageResult.Success = false;
            imageResult.ErrorMessage = ex.Message;
            return imageResult;
        }
    }
      // you can also create an Mvc dataannotation to validate the          extension of image in both server side and client side
      // don't forget to add (.JPG, .JPEG or .PNG on these extension, because you can facing this type of problem
  private bool ValidateExtension(string extension)
    {
        extension = extension.ToLower();
        switch (extension)
        {
            case ".jpg":
                return true;
            case ".png":
                return true;
            case ".gif":
                return true;
            case ".jpeg":
                return true;
            default:
                return false;
        }
    }

    private Image Scale(Image imgPhoto)
    {
        float sourceWidth = imgPhoto.Width;
        float sourceHeight = imgPhoto.Height;
        float destHeight = 0;
        float destWidth = 0;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

       // force resize, might distort image
        if (Width != 0 && Height != 0)
        {
            destWidth = Width;
            destHeight = Height;
        }
        // change size proportially depending on width or height
        else if (Height != 0)
        {
            destWidth = (float)(Height * sourceWidth) / sourceHeight;
            destHeight = Height;
        }
        else
        {
            destWidth = Width;
            destHeight = (float)(sourceHeight * Width / sourceWidth);
        }

        Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
                                    PixelFormat.Format32bppPArgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //you can also add these properties to improve the quality of saved image
    grPhoto.SmoothingMode = SmoothingMode.HighQuality;
        grPhoto.CompositingQuality = CompositingQuality.HighQuality;
        grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
            new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();

        return bmPhoto;
    }
 //you can also create another method to verify if a saved image with similar name exist and use it in som method of controller like (Modify your account
     public ImageResult VerifyUploadFile(HttpPostedFileBase file)
    {
        var fileName = Path.GetFileName(file.FileName);

        string finalFileName = UploadPath + fileName;

        // si une telle image existe déjà, renvoyer le nom du fichier et dire que le succes est faux
        if (System.IO.File.Exists
            (HttpContext.Current.Request.MapPath(UploadPath + finalFileName)))
        {
            //file exists => sucess is false
            return  new ImageResult { Success = false, ErrorMessage = null, ImageName =finalFileName  };
        }
        //file doesn't exist, upload item but validate first
        return RenameUploadFile(file);
    }
}

您可以根据需要在控制器中使用它

     [HttpPost]
     public ActionResult Index(FormCollection formCollection)
     {
     foreach (string item in Request.Files)
     {
    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
    if (file.ContentLength == 0)
        continue;
    if (file.ContentLength > 0)
    {
        // width + height will force size, care for distortion
        //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 };

        // height will increase the width proportionally
        //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 };

        // width will increase the height proportionally
        ImageUpload imageUpload = new ImageUpload { Width= 600 };

        // rename, resize, and upload
        //return object that contains {bool Success,string ErrorMessage,string ImageName}
        ImageResult imageResult = imageUpload.RenameUploadFile(file);
        if (imageResult.Success)
        {
            //TODO: write the filename to the db
            Console.WriteLine(imageResult.ImageName);
        }
        else
        {
            // use imageResult.ErrorMessage to show the error
            ViewBag.Error = imageResult.ErrorMessage;
        }
    }
}

  return View();
 }

您可以根据需要使用verifyupload。


2
投票
var imagePhysicalPath = @"c://image.jpg";
var newImagePhysicalPath = @"c://new-image.jpg";

var image = new System.Web.Helpers.WebImage(imagePhysicalPath)
.Resize(width + 1, height + 1, false, true)//+1 because webimage use 1px for border
.Crop(1, 1) //remove border
.Save(newImagePhysicalPath);
© www.soinside.com 2019 - 2024. All rights reserved.