我想减少图像尺寸并将缩小的图像保存到我的图像文件夹中。以下是我为保存图像所做的工作,但问题是缩小图像不会保存到我的图像文件夹中。
如何在MVC4中保存我的图像文件夹中的缩小图像?
以下是保存图片的代码:
public ActionResult AddProduct(TblProduct ObjProducts)
{
HttpPostedFileBase File = Request.Files[0];
if (ModelState.IsValid) {
string filename = Path.GetFileName(File.FileName);
string targetPath = Server.MapPath("Images/" + filename);
///save file
string oldImage = File.FileName;
string NewFileName = ObjProducts.ManualP_Id + ".JPG";
string pic = System.IO.Path.GetFileName(NewFileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Images/ProductImg"), NewFileName);
File.SaveAs(path);
ObjProducts.Image =NewFileName;
ObjProducts.IsActive = true;
ObjProducts.IsDelete = false;
ObjProducts.CreatedDate = DateTime.Now;
db.TblProducts.Add(ObjProducts);
db.SaveChanges();
return RedirectToAction("DisplayProduct", "PanelProduct");
}
return View();
}
答案 0 :(得分:1)
试试这个
Image img = Image.FromStream(httpPostedFileBase.InputStream, true, true);
var bitmap = new Bitmap(newWidth,newHeight);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img,
new Rectangle(0,0,newWidth,newHeight),
clipRectangle, GraphicsUnit.Pixel);
}
bitmap.Save(path,ImageFormat.Jpeg);
答案 1 :(得分:0)
您可以使用以下功能将图像缩放并压缩到所需的分辨率:
int Height = 600;
int Width = 800;
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;
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;
}