Is there any other way than saving the image to a stream to calculate how much it will be on disk?
I have an image variable containing a .png image.
To calculate how big it will be on disk, I currently pass it into a memory cache and then use the length of that "memory file" to figure out if it is in the file sizes I want.
Since this seems inefficient to me ("real" calculation is probably faster and less memory intensive) I am wondering if there is a way to do this differently.
Example:
private bool IsImageTooLarge(Image img, long maxSize)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
if (ms.ToArray().Length > maxSize)
{
return true;
}
}
return false;
}
More info: The source code is part of what the .dll will be, so web specific things won't work there as I need to do something with C #.
source to share
You can save some memory by implementing your own Stream
, say, PositionNullStream
which is similar to the class NullStream
behind Stream.Null
, but using a position counter. Your implementation will provide a write stream for the Save
image method only , and will collect the current position from it when finished Save
.
private bool IsImageTooLarge(Image img, long maxSize)
{
using (var ps = new PositionNullStream()) {
img.Save(ps, System.Drawing.Imaging.ImageFormat.Png);
return ps.Position > maxSize;
}
}
You can find an example implementation NullStream
on lines 1445..1454 here . Modify the implementation to preserve the current position when calling write and re-positioning methods ( NullStream
hardcoded to return zero).
source to share
No, there is no way. Because you don't want the image size, but the file size. The only way to achieve this - with anything to do with compression - is to compress it and see what happens.
Without it, you can say X * Y * Bytes Per Pixel - but this is a bitmap, not anything with compression.
source to share