如何获得& quot; System.Drawing.Image& quot;的文件大小 [英] How to get the file size of a "System.Drawing.Image"

查看:69
本文介绍了如何获得& quot; System.Drawing.Image& quot;的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data...

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

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

Im quite new to image manipulation but this is fine for getting simple values like width, height, aspect ratio etc but what I cannot work out is how to retrieve the physical file size of the jpg expressed in bytes. Any help would be much appreciated.

谢谢

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

Final solution including an MD5 hash of the image for later comparison

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

}

推荐答案

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

If you get your image directly from file, you can use the following code to get size of original file in bytes.

 var fileLength = new FileInfo(filePath).Length; 

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

If you get your image from other source, like getting one bitmap and composing it with other image, like adding watermark you will have to calculate size in run-time. You can't just use original file size, because compressing may lead to different size of output data after modification. In this case, you can use MemoryStream to save image to:

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

这篇关于如何获得&amp; quot; System.Drawing.Image&amp; quot;的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆