Check image file size in bytes

Image size is about 2.5 MB

This code gives me the correct size:

var fileLength = new FileInfo(path).Length;

This code gives me about 600KB

Image image= Image.FromFile(path);
byte[] imageByte = imageToByteArray(image);
long legnth= imageByte.Length;

public static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}

What am I missing?

The problem is that I get the image in byte [], so ..

+4
source share
3 answers
var fileLength = new FileInfo(path).Length;

looks like this:

byte[] buffer = System.IO.File.ReadAllBytes(@"yourimage.ext");
int size = buffer.Length;

System.Drawing.ImageThe object contains a raw bitmap. When you call imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png), the bitmap is compressed using a different image / compression algorithm or the same algorithm, but with different parameters, and therefore you have a difference in image size.

+3
source

This code is working fine.

//your filePath  ex: /document/mypersonal/ram.png
var fileLength = new FileInfo (FilePath).Length;
public static string GetFileSize(fileLength)
{
    string[] sizes = { "B", "KB", "MB", "GB" };
    int order = 0;
    while (fileLength >= 1024 && order + 1 < sizes.Length) {
        order++;
        fileLength = fileLength/1024;
    }
    string result = String.Format("{0:0.##} {1}", fileLength, sizes[order]);
    return result;
}
+1
source

When checking Lengthyour byte array, the problem is that, according to @Kuba Wyrostek, you most likely change the file format from a freely uncompressed bitmap to PNG, and then check the size, which will return a different value.

The most reliable value you can rely on will be

var fileLength = new FileInfo(path).Length;
0
source

All Articles