How to get the file size of a “System.Drawing.Image”

前端 未结 3 1712
夕颜
夕颜 2020-12-15 04:00

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 th

3条回答
  •  独厮守ぢ
    2020-12-15 04:19

    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; 
    

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

提交回复
热议问题