我目前正在编写一个系统,用于存储存储在传统图像库中的大约140,000个图像的元数据,这些图像正被移动到云存储中。我使用以下内容获取jpg数据...

System.Drawing.Image image = System.Drawing.Image.FromFile("filePath");

我对图像处理很新,但这对于获取宽度,高度,宽高比等简单值很好,但我无法解决的是如何检索以字节为单位表示的jpg的物理文件大小。任何帮助将不胜感激。

由于

最终解决方案包括图像的MD5哈希值以供以后比较

System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);

if (image != null)
{
  int width = image.Width;
  int height = image.Height;
  decimal aspectRatio = width > height ? decimal.divide(width, height) : decimal.divide(height, width);  
  int fileSize = (int)new System.IO.FileInfo(filePath).Length;

  using (System.IO.MemoryStream stream = new System.IO.MemoryStream(fileSize))
  {
    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
    Byte[] imageBytes = stream.GetBuffer();
    System.Security.Cryptography.MD5CryptoServiceProvider provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
    Byte[] hash = provider.ComputeHash(imageBytes);

    System.Text.StringBuilder hashBuilder = new System.Text.StringBuilder();

    for (int i = 0; i < hash.Length; i++)
    {
      hashBuilder.Append(hash[i].ToString("X2"));
    }

    string md5 = hashBuilder.ToString();
  }

  image.Dispose();

}
有帮助吗?

解决方案

如果直接从文件中获取图像,则可以使用以下代码以字节为单位获取原始文件的大小。

 var fileLength = new FileInfo(filePath).Length; 

如果从其他来源获取图像,例如获取一个位图并将其与其他图像合成,例如添加水印,则必须在运行时计算大小。您不能只使用原始文件大小,因为压缩可能会导致修改后输出数据的大小不同。在这种情况下,您可以使用MemoryStream将图像保存到:

long jpegByteSize;
using (var ms = new MemoryStream(estimatedLength)) // estimatedLength can be original fileLength
{
    image.Save(ms, ImageFormat.Jpeg); // save image to stream in Jpeg format
    jpegByteSize = ms.Length;
 }

其他提示

如果您没有原始文件,则文件大小不明确,因为它取决于图像格式和质量。所以你要做的就是将图像写入流(例如MemoryStream),然后使用流的大小。

System.Drawing.Image 不会给你文件长度的大小。你必须使用另一个库。

int len = (new System.IO.FileInfo(sFullPath)).Length;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top