我使用了文件上传器的控制器动作,我想在保存图像后压缩图像和压缩过程执行,所以我的问题是:我想只保存压缩图像并删除原始图像。但是此代码显示错误:文件,因为它正被另一个进程使用
我的代码是:
public ActionResult submitgeneralinfo(HttpPostedFileBase file, int? EmployeeId, GeneralInfoViewModel model)
{
var ext = Path.GetExtension(file.FileName);
uniquefilename = Convert.ToString(ID) + ext;
var path = Path.Combine(Server.MapPath("~/Attachements/GeneralInfodp/"), uniquefilename);
var compaths = Path.Combine(Server.MapPath("~/Attachements/GeneralInfodp/"), "com" + uniquefilename);
file.SaveAs(path);
file.InputStream.Dispose();
CompressImage(Image.FromFile(path), 30, compaths);
file.InputStream.Close();
file.InputStream.Dispose();
GC.Collect();
FileInfo file3 = new FileInfo(path);
if (file3.Exists)
{
file3.Delete(); // error :- file because it is being used by another process
}
}
private void CompressImage(Image sourceImage, int imageQuality, string savePath)
{
try
{
//Create an ImageCodecInfo-object for the codec information
ImageCodecInfo jpegCodec = null;
//Set quality factor for compression
EncoderParameter imageQualitysParameter = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, imageQuality);
//List all avaible codecs (system wide)
ImageCodecInfo[] alleCodecs = ImageCodecInfo.GetImageEncoders();
EncoderParameters codecParameter = new EncoderParameters(1);
codecParameter.Param[0] = imageQualitysParameter;
//Find and choose JPEG codec
for (int i = 0; i < alleCodecs.Length; i++)
{
if (alleCodecs[i].MimeType == "image/jpeg")
{
jpegCodec = alleCodecs[i];
break;
}
}
//Save compressed image
sourceImage.Save(savePath, jpegCodec, codecParameter);
}
catch (Exception e)
{
}
}
答案 0 :(得分:0)
使用WebImage
直接以低尺寸保存图像[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();
}