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?
JPEG files do not have a built-in resolution property. There are some common extensions to JPEG usage that can be used to provide the information, especially EXIF.
Unfortunately imwrite() has no way of writing EXIF data to JPEG files. https://www.mathworks.com/matlabcentral/answers/152559-writing-exif-data-to-jpg#answer_150208
As Jan points out, the resolution information is mostly informational. Most of the time it is wrong.
You should consider the JPEG resolution information as having only one purpose: namely that if you transmit a JPEG directly to your printer without using a print spooler (for example if you ftp the image to your printer) then the information will be used to figure out what printer DPI to use in printing the image. If you are using a print spooler, you should be setting parameters like "fit to page" or the like, and those parameters will override the resolution information stored in the JPEG file.