I found this method:
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap(\"winter.jpg\");
g.DrawImage(bmp, 0, 0);
Console.WriteLine(\"Screen resolution: \" + g.
"1024x768" is only called a "resolution" in the context of a computer's display settings, and even then it's an unfortunate misnomer. In imaging "1024x768" is simply the width & height of the image, so as others have mentioned, you've already shown the code that retrieves these numbers. Tweaked slightly:
var img = Image.FromFile(@"C:\image.jpg");
Console.WriteLine(img.Width + "x" + img.Height); // prints "1024x768" (etc)
The only built-in method to get the numbers you're after is by creating a new instance (and, in fact, decoding the entire image) - which is going to be highly inefficient if you need to retrieve just these numbers for several hundred images. Avoiding this is hard; here's a starting point: How do I reliably get an image dimensions in .NET without loading the image?
When you speak of "resolution" you normally refer to the number of dots, or pixels, per inch. The Bitmap
class stores this in the HorizontalResolution
/ VerticalResolution
properties, while the Graphics class in DpiX
/ DpiY
.
This calculation:
bmp.Width * (g.DpiX / bmp.HorizontalResolution)
can be rearranged for clarity as follows:
(bmp.Width / bmp.HorizontalResolution) * g.DpiX
where the bracketed part computes the width of the image in inches. Multiplying by g.DpiX
then gives you the number of pixels in the Graphics
object that have the same width in inches as the image bmp
.
Surely you've answered your own question, it's as simple as this:
Bitmap bmp = new Bitmap(@"winter.bmp");
Console.WriteLine("Image Width: " + bmp.Width);
Console.WriteLine("Image Height: " + bmp.Height);
The DPI info is really only useful when you are displaying or printing the image. In the sample code it is converting the image to a Graphics
object that can be used to draw it to the screen.
To answer the 2nd part of you question, you could parse the JPEG file header to find the width/height information without actually loading in the image. But to do this you'd need to know the header information and file format for JPEG files.
To get the size:
string path = @"C:\winter.jpg";
Image img = Image.FromFile(path);
Console.WriteLine("Image Width: " + img.Width); //equals img.Size.Width
Console.WriteLine("Image Height: " + img.Height); //equals img.Size.Height
Here's a full list of System.Drawing.Image properties, if case want to display others.
I'm not sure if there's a quicker way for an entire directory, with Windows Vista/7 there may be a newer API that contains this info, haven't come across it though.