cherry picked from:  https://github.com/blanton144/dimage
