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

℡╲_俬逩灬. 提交于 2019-11-28 22:49:23

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

If you don't have the original file, the file size is not clear as it depends on the image format and quality. So what you'd have to do is write the image to a stream (e.g. MemoryStream) and then use the stream's size.

MysticSlayer

System.Drawing.Image won't give you the file length of size. You have to use another library for that.

int len = (new System.IO.FileInfo(sFullPath)).Length;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!