Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 调整图像大小而不丢失质量MVC 4_Asp.net_.net_Asp.net Mvc_Asp.net Mvc 4_C# 4.0 - Fatal编程技术网

Asp.net 调整图像大小而不丢失质量MVC 4

Asp.net 调整图像大小而不丢失质量MVC 4,asp.net,.net,asp.net-mvc,asp.net-mvc-4,c#-4.0,Asp.net,.net,Asp.net Mvc,Asp.net Mvc 4,C# 4.0,我只想在不损失质量的情况下重新调整图像大小 我能用这个吗 [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(); } 或者调整WebIma

我只想在不损失质量的情况下重新调整图像大小 我能用这个吗

[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的大小但降低图像质量?
谢谢

这是我使用的代码。在操作中调用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;
    }
}
摘自

这是说,首先创建一个类的图像保存我只是复制和粘贴

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);
    }
}
然后你需要另一个类和方法来保存我只是复制和粘贴

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。

我只想知道我是如何填写参数orgFile upload Images的,因为我有一个错误GDI+中出现了一个通用错误。对于那些将面临此类问题的人,请查看此链接,我认为它会有所帮助
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);