Python:实用抓图工具开发介绍(含需求分析、设计、编码、单元测试、打包、系统测试、发布各环节)

  从今年1月份开始学习python以来,一直写一些很小的脚本文件,也主要是为了练习,今天花了些时间,写了一个还算功能齐全的小程序,并完成单元测试、系统测试、及打包等工作。与任何商业软件开发过程一样,小程序从无都有,也必须经历(需求分析、设计、编码、单元测试、打包、系统测试、发布各阶段),所以,借此,结合实现过程中遇到的问题,将此程序各环节做一个简单介绍,算做笔记,如果能对读者有所帮助,就再好不过了。


  一、需求分析

1、标题:

               开发一个可以快速抓图的小工具。

2、来源:

               自己。

3、背景:

               去年在工作中写过三四次软件操作指导书,step by step 的那种,这种指导书中难免会使用到各种操作界面的截图,有时需要全屏图片,有时需要当前窗口、更多时候需要 界面的部分图片,且需要将重点处使用红框做出标记,那时一直使用PrtSc键进行抓图,然后在画图板中编辑一下,最后在贴在word中,操作步骤多且单调,一定程度影响了工作效率。(由于公司不能上QQ,所以QQ相当方便的截图功能没法使用。)

4、价值:

              价值不大,网上应该有好多这样的工具,但对个人学习python倒是很有帮助。

5、约束:

               仅支持Windows环境上使用。


二、设计:

        不分什么概要设计和详细设计了,简单描述一下思路:

         通过使用pyhk模块提供的快捷键方式,注册3个快捷键(CTRL+F1/F2/F3),分别对应抓取三种不同的图片(全屏/当前窗口/任意区域),因用户习惯不尽相同,所以程序需要提供需要鼠标操作方式,此程序不是时时都使用,所以不能让它一直占用宽度有限的状态栏资源,故需要做成托盘程序,在托盘图标上通过鼠标右键点击弹出菜单项来进行抓图操作。

         画个简单的图:

          


                                                                   图1 用例图



三、编码:

       这一部分在前面的博文中已经讲过,见《Python:一个多功能的抓图工具开发(附源码)》《Python:程序最小化到托盘功能实现》,今天对这个程序做了些改动,最主要的是将这两个源码结合起来,并修正一些测试中发现的问题,最终代码如下,不再做详细解释。

  1、screenshot.py

#!/usr/bin/env python
#coding=gb2312

#此模块主要提供抓图功能,支持以下三种抓图方式:
#1、抓取全屏,快捷键CTRL+F1
#2、抓取当前窗口,快捷键CTRL+F2
#3、抓取所选区域,快捷键CTRL+F3
#抓到之后,会自动弹出保存对话框,选择路径保存即可
#*******************************************
#更新记录
#0.1 2012-03-10 create by dyx1024
#********************************************

import pyhk
import wx
import os
import sys
from PIL import ImageGrab
import ctypes
import win32gui
import ctypes.wintypes 
import screen_tray


def capture_fullscreen(SysTrayIcon):
    '''
    Function:全屏抓图
    Input:NONE
    Output: NONE
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-03-10
    '''  
    #抓图   
    pic = ImageGrab.grab()
    
    #保存图片
    save_pic(pic)
    
def capture_current_windows(SysTrayIcon = None):
    '''
    Function:抓取当前窗口
    Input:NONE
    Output: NONE
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-03-10
    ''' 
    #窗口结构       
    class RECT(ctypes.Structure):
        _fields_ = [('left', ctypes.c_long),
                ('top', ctypes.c_long),
                ('right', ctypes.c_long),
                ('bottom', ctypes.c_long)]
        def __str__(self):
            return str((self.left, self.top, self.right, self.bottom))
    
    rect = RECT()
    
    #获取当前窗口句柄
    HWND = win32gui.GetForegroundWindow()
    
    #取当前窗口坐标
    ctypes.windll.user32.GetWindowRect(HWND,ctypes.byref(rect))

    #调整坐标
    rangle = (rect.left+2,rect.top+2,rect.right-2,rect.bottom-2)
    
    #抓图
    pic = ImageGrab.grab(rangle)
    
    #保存
    save_pic(pic)
    
def capture_choose_windows(SysTrayIcon):
    '''
    Function:抓取选择的区域,没有自己写这个,借用QQ抓图功能
    Input:NONE
    Output: NONE
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-03-10
    '''     
    try:
         #加载QQ抓图使用的dll
         dll_handle = ctypes.cdll.LoadLibrary('CameraDll.dll') 
    except Exception:
             try:
                 #如果dll加载失败,则换种方法使用,直接运行,如果还失败,退出
                 os.system("Rundll32.exe CameraDll.dll, CameraSubArea")
             except Exception:
                 return    
    else:
         try:
             #加载dll成功,则调用抓图函数,注:没有分析清楚这个函数带的参数个数
             #及类型,所以此语句执行后会报参数缺少4个字节,但不影响抓图功能,所
             #以直接忽略了些异常
             dll_handle.CameraSubArea(0)
         except Exception:
             return           

def save_pic(pic, filename = '未命令图片.png'):
    '''
    Function:使用文件对框,保存图片
    Input:NONE
    Output: NONE
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-03-10
    '''     
    app = wx.PySimpleApp()
    
    wildcard = "PNG(*.png)|*.png"
    dialog = wx.FileDialog(None, "Select a place", os.getcwd(),
                           filename, wildcard, wx.SAVE)
    if dialog.ShowModal() == wx.ID_OK:
        pic.save(dialog.GetPath().encode('gb2312'))
    else:
        pass
    
    dialog.Destroy()    
 
class hook_kev_screenshot:
    def __init__(self):
        self.data = screen_tray.SysTrayIcon
        
    def capture_fullscreen(self):
        capture_fullscreen(self.data)
    
    def capture_current_windows(self):
        capture_current_windows(self.data)
        
    def capture_choose_windows(self):
        capture_choose_windows(self.data)
           

def screenshot_main():
    '''
    Function:主函数,注册快捷键
    Input:NONE
    Output: NONE
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-03-10
    '''         
        
    #创建hotkey句柄 
    hot_handle = pyhk.pyhk()
    
    fun = hook_kev_screenshot()
 
    #注册抓取全屏快捷键CTRL+F1
    hot_handle.addHotkey(['Ctrl', 'F1'], fun.capture_fullscreen)
    
    #注册抓取当前窗口快捷键CTRL+F2
    hot_handle.addHotkey(['Ctrl', 'F2'], fun.capture_current_windows)
    
    #注册抓取所选区域快捷键CTRL+F3
    hot_handle.addHotkey(['Ctrl', 'F3'], fun.capture_choose_windows)
 
    #开始运行
    hot_handle.start()
    
    
  2、screen_tray.py

#!/usr/bin/env python
#coding=gb2312

#!/usr/bin/env python
#coding=gb2312

#此模块主要将程序最小化到托盘,并可使用托盘上的菜单进行抓图操作
#同时提供快键键抓图,各快键定义如下::
#1、抓取全屏,快捷键CTRL+F1
#2、抓取当前窗口,快捷键CTRL+F2
#3、抓取所选区域,快捷键CTRL+F3
#抓到之后,会自动弹出保存对话框,选择路径保存即可
#程序中使用到类SysTrayIcon,可从以下站点获取:
#http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html

#*******************************************
#更新记录
#0.1 2012-04-07 create by dyx1024
#********************************************
         
import os
import sys
import win32api
import win32con
import win32gui_struct
import itertools, glob

import screenshot

try:
    import winxpgui as win32gui
except ImportError:
    import win32gui

class SysTrayIcon(object):
    '''TODO'''
    QUIT = 'QUIT'
    SPECIAL_ACTIONS = [QUIT]
    
    FIRST_ID = 1023
    
    def __init__(self,
                 icon,
                 hover_text,
                 menu_options,
                 on_quit=None,
                 default_menu_index=None,
                 window_class_name=None,):
        
        self.icon = icon
        self.hover_text = hover_text
        self.on_quit = on_quit
        
        menu_options = menu_options + (('退出', None, self.QUIT),)
        self._next_action_id = self.FIRST_ID
        self.menu_actions_by_id = set()
        self.menu_options = self._add_ids_to_menu_options(list(menu_options))
        self.menu_actions_by_id = dict(self.menu_actions_by_id)
        del self._next_action_id
        
        
        self.default_menu_index = (default_menu_index or 0)
        self.window_class_name = window_class_name or "SysTrayIconPy"
        
        message_map = {win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart,
                       win32con.WM_DESTROY: self.destroy,
                       win32con.WM_COMMAND: self.command,
                       win32con.WM_USER+20 : self.notify,}
        # Register the Window class.
        window_class = win32gui.WNDCLASS()
        hinst = window_class.hInstance = win32gui.GetModuleHandle(None)
        window_class.lpszClassName = self.window_class_name
        window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW;
        window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
        window_class.hbrBackground = win32con.COLOR_WINDOW
        window_class.lpfnWndProc = message_map # could also specify a wndproc.
        classAtom = win32gui.RegisterClass(window_class)
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = win32gui.CreateWindow(classAtom,
                                          self.window_class_name,
                                          style,
                                          0,
                                          0,
                                          win32con.CW_USEDEFAULT,
                                          win32con.CW_USEDEFAULT,
                                          0,
                                          0,
                                          hinst,
                                          None)
        win32gui.UpdateWindow(self.hwnd)
        self.notify_id = None
        self.refresh_icon()
        
        #由于HOT KEY也要捕获消息,故此处暂不处理,在HOT KEY中统一处理,否则快捷键无法注册使用
        #win32gui.PumpMessages()

    def _add_ids_to_menu_options(self, menu_options):
        result = []
        for menu_option in menu_options:
            option_text, option_icon, option_action = menu_option
            if callable(option_action) or option_action in self.SPECIAL_ACTIONS:
                self.menu_actions_by_id.add((self._next_action_id, option_action))
                result.append(menu_option + (self._next_action_id,))
            elif non_string_iterable(option_action):
                result.append((option_text,
                               option_icon,
                               self._add_ids_to_menu_options(option_action),
                               self._next_action_id))
            else:
                print 'Unknown item', option_text, option_icon, option_action
            self._next_action_id += 1
        return result
        
    def refresh_icon(self):
        # Try and find a custom icon
        hinst = win32gui.GetModuleHandle(None)
        if os.path.isfile(self.icon):
            icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
            hicon = win32gui.LoadImage(hinst,
                                       self.icon,
                                       win32con.IMAGE_ICON,
                                       0,
                                       0,
                                       icon_flags)
        else:
            print "Can't find icon file - using default."
            hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)

        if self.notify_id: message = win32gui.NIM_MODIFY
        else: message = win32gui.NIM_ADD
        self.notify_id = (self.hwnd,
                          0,
                          win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP,
                          win32con.WM_USER+20,
                          hicon,
                          self.hover_text)
        win32gui.Shell_NotifyIcon(message, self.notify_id)

    def restart(self, hwnd, msg, wparam, lparam):
        self.refresh_icon()

    def destroy(self, hwnd, msg, wparam, lparam):
        if self.on_quit: self.on_quit(self)
        nid = (self.hwnd, 0)
        win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
        win32gui.PostQuitMessage(0) # Terminate the app.

    def notify(self, hwnd, msg, wparam, lparam):
        if lparam==win32con.WM_LBUTTONDBLCLK:
            self.execute_menu_option(self.default_menu_index + self.FIRST_ID)
        elif lparam==win32con.WM_RBUTTONUP:
            self.show_menu()
        elif lparam==win32con.WM_LBUTTONUP:
            pass
        return True
        
    def show_menu(self):
        menu = win32gui.CreatePopupMenu()
        self.create_menu(menu, self.menu_options)
        #win32gui.SetMenuDefaultItem(menu, 1000, 0)
        
        pos = win32gui.GetCursorPos()
        # See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/menus_0hdi.asp
        win32gui.SetForegroundWindow(self.hwnd)
        win32gui.TrackPopupMenu(menu,
                                win32con.TPM_LEFTALIGN,
                                pos[0],
                                pos[1],
                                0,
                                self.hwnd,
                                None)
        win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
    
    def create_menu(self, menu, menu_options):
        for option_text, option_icon, option_action, option_id in menu_options[::-1]:
            if option_icon:
                option_icon = self.prep_menu_icon(option_icon)
            
            if option_id in self.menu_actions_by_id:                
                item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
                                                                hbmpItem=option_icon,
                                                                wID=option_id)
                win32gui.InsertMenuItem(menu, 0, 1, item)
            else:
                submenu = win32gui.CreatePopupMenu()
                self.create_menu(submenu, option_action)
                item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
                                                                hbmpItem=option_icon,
                                                                hSubMenu=submenu)
                win32gui.InsertMenuItem(menu, 0, 1, item)

    def prep_menu_icon(self, icon):
        # First load the icon.
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
        hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE)

        hdcBitmap = win32gui.CreateCompatibleDC(0)
        hdcScreen = win32gui.GetDC(0)
        hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
        hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
        # Fill the background.
        brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
        win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
        # unclear if brush needs to be feed.  Best clue I can find is:
        # "GetSysColorBrush returns a cached brush instead of allocating a new
        # one." - implies no DeleteObject
        # draw the icon
        win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
        win32gui.SelectObject(hdcBitmap, hbmOld)
        win32gui.DeleteDC(hdcBitmap)
        
        return hbm

    def command(self, hwnd, msg, wparam, lparam):
        id = win32gui.LOWORD(wparam)
        self.execute_menu_option(id)
        
    def execute_menu_option(self, id):
        menu_action = self.menu_actions_by_id[id]      
        if menu_action == self.QUIT:
            win32gui.DestroyWindow(self.hwnd)
        else:
            menu_action(self)
            
def non_string_iterable(obj):
    try:
        iter(obj)
    except TypeError:
        return False
    else:
        return not isinstance(obj, basestring)
    
def help_text(sysTrayIcon):
    '''
    Function:显示帮助文件
    Input:even
    Output: Ture
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-04-07
    '''   
    
    help_info = '''
                                                            使用指导
                                                            
    本工具提供抓图功能(包括全屏、当前窗口、任意区域),且有两种操作方式:
    一、程序运行后,在桌面右下脚托盘图标上点右键,选择弹出的菜单项进行抓图操作。
    二、通过快捷键进行操作,各快捷键定义如下:
    1、抓取全屏,快捷键CTRL+F1
    2、抓取当前窗口,快捷键CTRL+F2
    3、抓取所选区域,快捷键CTRL+F3 
    '''
    win32api.MessageBox(0, help_info, "帮助信息")
		
if __name__ == '__main__':
    '''
    Function:主程序,提供托盘及快捷键操作两种方式抓图
    Input:even
    Output: Ture
    author: socrates
    blog:http://blog.csdn.net/dyx1024
    date:2012-04-07
    '''   
    #托盘图标所在位置
    icon_file = os.path.join(os.getcwd(), "datafile\screenshot.ico")
    if os.path.exists(icon_file):
        icons = icon_file
    else:
        icons = os.getenv('WINDIR') + "\SYSTEM32\orange-install.ico"
    
    #托盘鼠标停留提示
    hover_text = "多功能抓图工具"
    
    #托盘右键菜单项
    menu_options = (('抓取全屏(CTRL+F1)', icons, screenshot.capture_fullscreen),
                    ('抓取当前窗口(CTRL+F2)', icons, screenshot.capture_current_windows),
                    ('抓取所选区域(CTRL+F3)', icons, screenshot.capture_choose_windows),
                    ('帮助', icons, help_text)
                   )
    #退出程序
    def bye(sysTrayIcon): pass
    
    #设置托盘
    SysTrayIcon(icons, hover_text, menu_options, on_quit=bye)
    
    #注册快捷键
    screenshot.screenshot_main()


四、单元测试

  我使用的IDE为Eclipse+pyDev,功能强大,操作简单、可直接打断点进行逐语句调试,过程不介绍了,贴张图上来。


                                                                                                                                     图2 单元测试


五、打包:

    这一部分浪费时间较多,在之前的文章《Python:程序发布方式简介一(打包为可执行文件EXE)》中介绍了py2exe工具的所用,但如文章所述,打包出的exe文件有些动态库是没有被包含的,导致部分机器上执行失败。本次使用了另一个python打包工具Pyinstaller,此工具简单,只需要三步操作,可从http://www.pyinstaller.org/下载此工具。说一下操作步骤:

     1、解压下载后的文件到任意目录,如E:\pyinstaller-1.5.1。

     2、执行Configure.py。

     3、将开发的python程序,相关文件、ico图标文件拷到E:\pyinstaller-1.5.1目录下。

     4、执行Makespec.py -F -w -X screen_tray.py,执行后生成规则文件screen_tray.spec,内容如下,可手动编辑。

# -*- mode: python -*-
a = Analysis([os.path.join(HOMEPATH,'support\\_mountzlib.py'), os.path.join(HOMEPATH,'support\\useUnicode.py'), 'screen_tray.py'],
             pathex=['E:\\pyinstaller-1.5.1'])
pyz = PYZ(a.pure)
exe = EXE( pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=os.path.join('dist', 'screen_tray.exe'),
          debug=False,
          strip=False,
          upx=True,
          console=False , icon='screenshot_tray.ico')
app = BUNDLE(exe,
             name=os.path.join('dist', 'screen_tray.exe.app'))
    5、执行>Build.py E:\pyinstaller-1.5.1\screen_tray/screen_tray.spec打包。

    6、成功后,在E:\pyinstaller-1.5.1\screen_tray\dist目录下生成screen_tray.exe文件。

     

                                                                                     图3 打包后的文件

    7、由于托盘程序需要使用一个ico图标,这个文件我一直没有办法打包进exe,浪费很多时间后放弃,所以在软件发布时在exe文件所在上目录中建立了一个子目录datafile,其中存放图标,用户也可替换为自己的,只要文件名不变就行。程序中也做了些容错处理,如果目录不存在,则从系统目录下加载一个。如下:

    #托盘图标所在位置
    icon_file = os.path.join(os.getcwd(), "datafile\screenshot.ico")
    if os.path.exists(icon_file):
        icons = icon_file
    else:
        icons = os.getenv('WINDIR') + "\SYSTEM32\orange-install.ico"

    8、Pyinstaller使用方便,不足之处是它打包的EXE文件比较大,所以这个小工具有9M大小。


六、系统测试:

    直接运行一下看看,依然上图:

     1、执行screen_tray.exe,托盘显示正常。

     

                               图4 托盘显示测试

      2、菜单项目测试,正常。

      

                                                                 图5 菜单项测试

     3、抓取功能正常(快捷键及菜单项)

                                                                                                           图6 抓图功能测试(任意区域)

  4、帮助菜单正常。

   

                                          图7 帮助功能测试(任意区域)

   其他测试点就不一一写了,累了。


七、发布:

     好像没地方发布,目前就我一个用户。

     连同源码一并上传到资源中,感兴趣的朋友可以试用,全当学习交流哈~

     地址:http://download.csdn.net/detail/dyx1024/4206549


八、结束:

    电脑前坐了一整天,去公园逛逛。

    归来,附所拍照片一张,纯属娱乐,与本文无关~~

   


  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值