【问题标题】:Upload image file size is more than actual file size上传图片文件大小大于实际文件大小
【发布时间】:2018-02-24 16:55:03
【问题描述】:

我正在使用 fileapi 插件在 c# 中上传图像。我的实际文件大小为 60kb,但上传后文件大小在服务器上显示为 350kb。为什么会这样?这是我保存图像的代码:

    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);

    }

谁能告诉我我的代码有什么问题?我正在设计图像尺寸必须很小的购物车。缩略图 (png) 也需要更多的大小 200kb

【问题讨论】:

  • 好吧,您没有保存原始流 - 您正在使用 GetThumbnailImage 转换它。要获得原始数据大小,只需保存原始流 - 检查它是否有效。然后,如果您想研究调整大小等,您可以将该方面与上传方面完全分开。
  • 我已经尝试过了。也与原始流相同的问题。
  • 请确认您实际上是在询问如何应用图像压缩...如果是这样,那是骗人的:stackoverflow.com/questions/1484759/…
  • 请显示使用原始流的代码。看到这真的会造成问题,我会感到惊讶。
  • 顺便说一句,我强烈建议不要为此使用DateTime.Now - 使用DateTime.UtcNow 以避免因时区而造成混淆。

标签: c# asp.net-mvc-4 image-processing fileapi


【解决方案1】:

最终大小很可能会增加,因为您没有在 img.Save() 方法上传递图像格式。

你应该改变

img.Save(Path.ChangeExtension(filePath, "jpeg"));

img.Save(Path.ChangeExtension(filePath, "jpeg"), ImageFormat.Jpeg);

对于 png 图像也是如此 (ImageFormat.Png)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多