实现代码:pywin32截图后将数据转为tkimage格式然后释放之前的图片
时间: 2023-06-20 22:05:07 浏览: 152
以下是实现代码,包括截图、转换为Tkinter Image、释放之前的图片:
```python
import win32gui
import win32ui
import win32con
import win32api
import tkinter as tk
from PIL import Image, ImageTk
# 获取屏幕DC
hdesktop = win32gui.GetDesktopWindow()
desktop_dc = win32gui.GetWindowDC(hdesktop)
img_dc = win32ui.CreateDCFromHandle(desktop_dc)
# 获取屏幕尺寸
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
# 创建一个设备描述表
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(img_dc, width, height)
img_dc.SelectObject(bitmap)
# 截图
img_dc.BitBlt((0, 0), (width, height), desktop_dc, (left, top), win32con.SRCCOPY)
# 转换为PIL Image
bmp_info = bitmap.GetInfo()
bmp_stride = (bmp_info['bmWidth'] * bmp_info['bmBitsPixel'] + 31) // 32 * 4
raw_data = bitmap.GetBitmapBits(True)
pil_img = Image.frombuffer('RGB',
(bmp_info['bmWidth'], bmp_info['bmHeight']),
raw_data,
'raw',
'BGRX',
bmp_stride)
# 转换为Tkinter Image
tk_img = ImageTk.PhotoImage(pil_img)
# 释放之前的图片
bitmap.DeleteObject()
img_dc.DeleteDC()
win32gui.ReleaseDC(hdesktop, desktop_dc)
# 使用Tkinter显示截图
root = tk.Tk()
root.geometry('{}x{}'.format(width, height))
canvas = tk.Canvas(root, width=width, height=height)
canvas.pack()
canvas.create_image(0, 0, image=tk_img, anchor=tk.NW)
root.mainloop()
```
阅读全文