29

私は現在、クラウド ストレージに移動されている従来の画像ライブラリ内に保存されている約 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();

}
4

3 に答える 3

55

ファイルから直接画像を取得する場合、次のコードを使用して元のファイルのサイズをバイト単位で取得できます。

 var fileLength = new FileInfo(filePath).Length; 

透かしを追加するなど、1 つのビットマップを取得して他の画像と合成するなど、他のソースから画像を取得する場合は、実行時にサイズを計算する必要があります。圧縮すると、変更後の出力データのサイズが異なる可能性があるため、元のファイル サイズをそのまま使用することはできません。この場合、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;
 }
于 2008-10-21T10:01:26.953 に答える
2

元のファイルがない場合、ファイル サイズは画像の形式と品質に依存するため明確ではありません。したがって、画像をストリーム (MemoryStream など) に書き込んでから、ストリームのサイズを使用する必要があります。

于 2008-10-21T10:06:10.003 に答える
1

System.Drawing.Imageサイズのファイル長はわかりません。そのためには別のライブラリを使用する必要があります。

int len = (new System.IO.FileInfo(sFullPath)).Length;
于 2008-10-21T10:03:23.690 に答える