I am uploading an image in c# using a fileapi plugin. My actual file size is 60kb but after uploading the file size appears as 350kb on the server. Why is this happening? Here is my code for saving an image:
public JsonResult SaveImageFile(byte[] file)
{
var filesData = Request.Files[0];
string fileName = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
if (filesData != null && filesData.ContentLength > 0)
{
string directoryPath = Path.Combine(Server.MapPath("~/Images/Products/"), itemId);
string filePath = Path.Combine(Server.MapPath("~/Images/Products/"), itemId, fileName+".jpeg");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
Image img = Image.FromStream(filesData.InputStream, true, true);
img = img.GetThumbnailImage(800, 600, () => false, IntPtr.Zero);
img.Save(Path.ChangeExtension(filePath, "jpeg"));
Image thumb = img.GetThumbnailImage(411, 274, () => false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(filePath, "png"));
ViewBag.MimeType = "image/pjpeg";
TempData["ItemFilePath"] = "~/Images/Products/" + itemId +"/"+ fileName+".jpeg";
TempData["ItemThumbnailFilePath"] = "~/Images/Products/" + itemId + "/" + fileName + ".png";
TempData["ItemFileName"] = fileName + ".jpeg";
}
return Json(new
{
Success = true,
Title = "Success",
FileName = relativePath
}, JsonRequestBehavior.AllowGet);
}
Can anyone tell me what is the problem with my code? I am designing shopping cart in which image size must be small. The thumbnail image (png
) also taking more size 200kb
The final size is most likely increasing because you're not passing your image format on img.Save()
method.
You should change
img.Save(Path.ChangeExtension(filePath, "jpeg"));
to
img.Save(Path.ChangeExtension(filePath, "jpeg"), ImageFormat.Jpeg);
Same for the png image (ImageFormat.Png)