部分代碼思路來源於互聯網html
以前一直在尋找一種完美的移動設備屏幕流回傳方案,這種嘗試一旦成功便可運用於多種平臺,好比雲端測試Portal中對機器設備屏幕的實時監控,再輔以html5強大的特性,能夠直接在web上模擬手機操做,達到"遠程監控"的目的,本demo的部分思路來源於互聯網,我嘗試用jython所有重寫了一遍,這種方式實現起來雖然比較"土鱉",可是效果基本能夠符合需求,下面是效果圖和代碼清單。html5
#!/usr/bin/env python # -*- coding:utf-8 -*- # Android_ScreenSream by Archer # Based on Jython,ddmlib #import jar import sys,os sys.path.append(r'C:\\ddmlib.jar') sys.path.append(r'C:\\guava17.jar') sys.path.append(r'C:\\rt.jar') from threading import Thread #import lib from java.awt.image import * from java.io import * from javax.imageio import * from com.android.ddmlib import * from time import sleep class AndroidScreenStream(object): def __init__(self): super(AndroidScreenStream,self).__init__() self.devices=[] self.currentdevice=None self.rawimgdata=None self.rawscreen=None def wait_device_lists(self,bridge): """獲取設備列表信息""" count=0 while(bridge.hasInitialDeviceList()==False): try: sleep(0.5) count+=1 except: pass if(count>60): print "獲取設備列表信息超時!" break def get_devices(self): """獲取全部已鏈接設備""" AndroidDebugBridge.init(False) mybridge=AndroidDebugBridge.createBridge() self.wait_device_lists(mybridge) #get self.devices.append(mybridge.getDevices()) return self def get_device_by_index(self,index): """根據index獲取單個當前設備""" AndroidDebugBridge.init(False) mybridge=AndroidDebugBridge.createBridge() self.wait_device_lists(mybridge) #get try: self.currentdevice=mybridge.getDevices()[index] return self except IndexError: print "不存在序號爲"+str(index)+"的設備,請檢查USB鏈接!" sys.exit() def get_current_screen_imgbyes(self): """獲取當前屏幕圖像的字節數據""" self.rawimgdata=self.currentdevice.getScreenshot().data #保存圖像字節數據 return self def get_current_rawscreen(self): """保存當前屏幕screen對象""" self.rawscreen=self.currentdevice.getScreenshot() return self def save_screen_img(self,path=os.path.join(os.getcwd(),'current_frame.jpeg'),islandscape=False): """將當前屏幕圖像數據保存爲圖片""" if self.rawscreen is not None: landscape=islandscape #橫屏尺寸處理 imgwidth=self.rawscreen.height if landscape else self.rawscreen.width imgheight=self.rawscreen.width if landscape else self.rawscreen.height image=BufferedImage(imgwidth,imgheight,BufferedImage.TYPE_INT_RGB) if image.getHeight()!=imgheight or image.getWidth()!=imgwidth: image=BufferedImage(imgwidth,imgheight,BufferedImage.TYPE_INT_RGB) index=0 indexInc=self.rawscreen.bpp>>3 for y in range(self.rawscreen.height): for x in range(self.rawscreen.width): value=self.rawscreen.getARGB(index) if landscape: image.setRGB(y,self.rawscreen.width-x-1,value) else: image.setRGB(x,y,value) index+=indexInc try: ImageIO.write(image,"JPEG",File(path)) except IOError: print "發生異常!" sys.exit() else: print "rawscreen爲空!" sys.exit() if __name__=="__main__": ASS=AndroidScreenStream() ShotDevice=ASS.get_device_by_index(0) while True: ShotDevice.get_current_rawscreen().save_screen_img()