Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine jpeg filesize without actually saving the jpeg

I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;

But because of the slow disk access, the program takes too long. Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

like image 224
lupedito Avatar asked Dec 16 '22 15:12

lupedito


2 Answers

You can write the image data to a Stream instead of supplying a filename:

using (MemoryStream mem = new MemoryStream())
{
    frameNormal.Save(mem, ImageFormat.Jpeg);
    filesizeJPG = mem.Length;
}
like image 187
C.Evenhuis Avatar answered Feb 03 '23 19:02

C.Evenhuis


You can to something like this:

MemoryStream tmpMs = new MemoryStream();
frameNormal.Save(tmpMs, ImageFormat.Jpeg);
long fileSize = tmpMs.Length;
like image 45
HABJAN Avatar answered Feb 03 '23 18:02

HABJAN