截取屏幕的工作原理
读缓冲区--》生成可压缩位图--》压缩位图--》生成PNG格式文件
截屏的开源项目地址:http://code.google.com/p/android-fb2png/source/checkout
代码备忘
public void acquireScreenshot(Context mContext) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager WM = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = WM.getDefaultDisplay(); display.getMetrics(metrics); int height = metrics.heightPixels; // 屏幕高 int width = metrics.widthPixels; // 屏幕的宽 int pixelformat = display.getPixelFormat(); PixelFormat localPixelFormat1 = new PixelFormat(); PixelFormat.getPixelFormatInfo(pixelformat, localPixelFormat1); int deepth = localPixelFormat1.bytesPerPixel;// 位深 byte[] arrayOfByte = new byte[height* width* deepth]; long tmp = System.currentTimeMillis(); try { InputStream localInputStream = readAsRoot(new File( "/dev/graphics/fb0")); DataInputStream localDataInputStream = new DataInputStream( localInputStream); android.util.Log.e("mytest", "-----read start-------"); localDataInputStream.readFully(arrayOfByte); android.util.Log.e("mytest", "-----read end-------time = " + (System.currentTimeMillis() -tmp )); localInputStream.close(); FileOutputStream out = new FileOutputStream(new File( "/mnt/sdcard/1.png")); int[] tmpColor = new int[width * height]; int r, g, b; tmp = System.currentTimeMillis(); android.util.Log.e("mytest", "-----bitmap start-------"); for (int j = 0; j < width * height * deepth; j+=deepth) { b = arrayOfByte[j]&0xff; g = arrayOfByte[j+1]&0xff; r = arrayOfByte[j+2]&0xff; tmpColor[j/deepth] = (r << 16) | (g << 8) | b |(0xff000000); } Bitmap tmpMap = Bitmap.createBitmap(tmpColor, width, height, Bitmap.Config.ARGB_8888); android.util.Log.e("mytest", "-----bitmap end-------time = " + (System.currentTimeMillis() -tmp )); tmp = System.currentTimeMillis(); android.util.Log.e("mytest", "-----compress start-------"); tmpMap.compress(Bitmap.CompressFormat.PNG, 100, out); android.util.Log.e("mytest", "-----compress end-------time = " + (System.currentTimeMillis() -tmp )); out.close(); } catch (Exception e) { android.util.Log.e("mytest", "Exception"); e.printStackTrace(); } } public static InputStream readAsRoot(File paramFile) throws Exception { Process localProcess = Runtime.getRuntime().exec("su"); String str = "cat " + paramFile.getAbsolutePath() + "\n"; localProcess.getOutputStream().write(str.getBytes()); return localProcess.getInputStream(); }