Android: Taking Screenshots of the Emulator from Commandline

There are a number of reasons why you may want to grab a screenshot of your Android app. In Eclipse, DDMS perspective provides an easy way to do it via the UI:

DDMS Perspective

However, UI features like this are hard to automate and sometimes it can be handy to be able to grab the screen from command line via a script. Welll..

Android Tales pointed me in a direction of the old platform source that claimed to do just that. The newer source versions do not include the ScreenShot.java utility, so I had to grab an old one here. So I followed the directions and got the old stub here, added ddmlib and Screenshot.java classes to the same project, compiled, ran in on a loaded AVD with v2.2 and…

Got the same error that one of the commenters at Android Tales:

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

Diving into the code for a quick hour, I determined that the dimensions of the screen were wrong (in my case 400×768000). Further, I determined that the dimensions are reported by the device in response to ‘framebuffer:’ request. Finally, I deduced that the 768000 value was really the size of the buffer I should be allocating to hold the screenshot, since I knew my height was 960 and it’s 16 bits per pixel. So in short, i determined that the response format has changed.

And thus, I trial and errored it to work.. mostly…

In AdbHelper.java, in the getFrameBuffer mothod, you need to modify the section where it parses the reply to read:

...
...
buf.order(ByteOrder.LITTLE_ENDIAN);
int status = buf.getInt(); // this is the status int maybe?? (seems to be 1)
imageParams.bpp = buf.getInt(); // this appears to be BITS per pixel
imageParams.size = buf.getInt(); // overall image size
imageParams.width = buf.getInt(); // the height of the image
imageParams.height = (imageParams.size / imageParams.width) / (imageParams.bpp / 8);
...
...

Hope this helps,

Cheers!