There i no general method to do this. At first you have to clarify what type of "images" your are talking of. If you e.g. have a photo of a ruler or a meter stick, you can count the pixels between marks. But if you have a PNG of a bird or a screenshot of a Matlab figure, what does "DPI" mean at all?
"DPI" is meaningful only, if you display the image, e.g. by showing it on the screen (then the DPI of the screen matters) or by printing it on paper. But of course you can print the same image on a paper with the double size using the half DPI value and get the same information.
Therefore I think, an image does not have a meaningful DPI value in general. Only printing to paper or to a EPS/PDF file define the DPI value uniquely. But then looking in the meta-data of the file is required.
So please explain which problem you want to solve actually. What is the problem with using imfinfo?