Python剪切板提取、截图、图⽚粘贴,操作汇总
⽬录
1. PIL::ImageGrab(不适⽤于Linux)
只适⽤于Windows & MacOS系统。Linux系统⽀持XCB的X11,。
1.1. 截图Grab
>>> im = ab()
>>> im.size
(1366, 768)
>>> im2 = ab((300, 100, 1400, 600))
>>> de
'RGB'
1.2. Grabclipboard
截⾄v7.1.2,尚不⽀持Linux系统,。
含义:抓取当前剪贴板的快照,返回⼀个模式为“RGB”的图像或者⽂件名称的列表。如果剪贴板不包括图像数据,这个函数返回空。⽤户可以使⽤函数isinstance()来检查该函数返回的是⼀个有效图像对象或者其他数据。
from PIL import Image, ImageGrab
im = abclipboard()
if isinstance(im, Image.Image):
print "Image: size : %s, mode: %s" % (im.size, im.mode)
im.save("D:\\Document\\mdoc\\python\\pic\\12\\grab_grabclipboard.jpg")
elif im:
for filename in im:
try:
print "filename: %s" % filename
im = Image.open(filename)
except IOError:
pass #ignore this file
else:
print "ImageList: size : %s, mode: %s" % (im.size, im.mode)
else:
print "clipboard is empty."
1.2.1. Error: 'NoneType' object has no attribute 'save'
官⽅⽂档有说明,grabclipboard()函数有⼀个缓存的问题,操作太快,有时候它就会读取上⼀次的内容,因为第⼀个没有读取到图像,所以报错了。
所以解决⽅案也很简单,既然是操作太快导致读取了缓存,那就让它慢⼀点呗,我们加上⼀个时间的延迟就可以了: time.sleep(0.1)。
2. MSS: 多屏截屏⼯具
MSS stands for Multiple Screen Shots.
2.1. 安装
You can install it with pip:
python -m pip install -U --user mss
Or you can install it with conda:
conda install -c conda-forge python-mss
2.2. 使⽤
结合PIL使⽤。
import mss
from PIL import Image
with mss.mss() as sct:
# Get rid of the first, as it represents the "All in One" monitor:
for num, monitor in itors[1:], 1):
# Get raw pixels from the screen
sct_img = ab(monitor)
# Create the Image
img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
# The same, but less efficient:
# img = Image.frombytes('RGB', sct_img.size, b)
# And save it!
output = "monitor-{}.png".format(num)
img.save(output)
print(output)
3. pyscreenshot: 截图⼯具
其⽬标是,适配多种backend,表现为PIL.ImageGrab的调⽤形态。
import pyscreenshot as ImageGrab
im = ab()
im2 = np.asanyarray(im)
4. pyperclip
pyperclip只⽀持⽂本内容,windows下不依赖其它第三⽅库,⾮常轻量易⽤。
pip install pyperclip
使⽤⽰例
>>> import pyperclip
>>> dd = pyperclip.paste()
>>> print(dd)
python⼤法好!
>>> py("")
>>> pyperclip.paste()
''
5. 调⽤其他程序实现
⽬前Linux和Mac,对剪切板的操作原⽣⽀持还不是很完善(说⽩了,就是不⾏……),⽽且如果不是⾃⼰写脚本的话很难原⽣⽀持剪切板⾥的图⽚读取和写⼊。
5.1. MacOS for text
⾃带pbcopy和pbpaste⼯具。
# 写⼊剪切板
$ echo 'hihihi' | pbcopy
#或
$ pbcopy < echo 'hello'
# 读取剪切板
$ pbpaste
# 保存剪切板内容到⽂件
$ pbpaste > ~/
5.2. MacOS::pngpaste
⽬前没有原⽣⽀持剪切板的⽂字之外的类型。所以必须要下载第三⽅应⽤。
pngpaste : 最简单的剪切板图像转⽂件⼯具.
不⽀持直接在⽂件上ctrl+c这样拷贝来的图⽚
不⽀持gif
5.3. xclip
原本是在linux常⽤的剪切板操控⼯具,后来可能流⾏起来在mac也⽀持了。
粘贴图⽚的关键在于-t选项:
1. See what targets are available:
$ xclip -selection clipboard -t TARGETS -o
TARGETS
image/png
text/html
2. Note the image/png target; go ahead and get it:
$ xclip -selection clipboard -t image/png -o > /tmp/avatar.png
$ see /tmp/avatar.png    # yep, that's it
不过,令⼈郁闷的是,在我的 Xubuntu20.04 中,xclip(v0.13)并不⽀持image/png,原因未知。
额,是⽀持的——原来这个命令是动态检测当前剪切板内容的格式,⽽不是静态测试所有⽀持的类型。先复制⼀张图⽚,就可以看到打印出了image/png项。
具体使⽤⽅法,可以参考以下代码:
import subprocess
CMD_XCLIP = {
"has_jpg"  : "xclip -selection clipboard -t TARGETS -o | grep image/jpeg",  # .split()
"has_png"  : "xclip -selection clipboard -t TARGETS -o | grep image/png",
"has_txt"  : "xclip -selection clipboard -t TARGETS -o | grep text/plain;charset=utf-8",
"save_jpg"  : "xclip -selection clipboard -t image/jpeg -o > ",
"save_png"  : "xclip -selection clipboard -t image/png -o > ",
"get_txt"  : "xclip -selection clipboard -t text/plain -o",
}
def call_xclip(file_name):
def run_shell(key, path_save=None):
str_cmd = CMD_XCLIP[key]
if path_save:
str_cmd += path_save
proc = subprocess.run(str_cmd,
shell=True,
# stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
return proc.stdout
if run_shell("has_jpg"):  # != b"":
run_shell("save_jpg", file_name)
return b"img\n"
elif run_shell("has_png"):
run_shell("save_png", file_name)
# 格式转换
subprocess.call("mogrify -format jpg {}".format(file_name), shell=True)
return b"img\n"
elif run_shell("has_txt") != b"":
txt = run_shell("get_txt")
return  # bytes
return b"err\n"
5.4. gpaste
看上去很强⼤(⽀持剪切板图⽚操作),直接使⽤apt install gpaste就可以成功安装了,还提供了libgpaste-dev⽤于功能调⽤。安装之后,系统会提供⼀个 gpaste-daemon 的后台进程,⽽⽤户则是调⽤ gpaste-client 客户端实现操作。
不过……我的Xubuntu系统环境下,似乎对该程序的⽀持并不友好。
5.5. parcellite
同样是使⽤GTK+开发的剪切板⼯具。直接使⽤sudo apt install parcellite安装即可使⽤。
⽀持编辑剪切板
全局快捷键
不⽀持图像的处理
⽀持⾃定义Action
⼀款中规中矩的产品,但运⾏⽐较稳定,不会出什么岔⼦。
6. 终极解决⽅案
6.1. Qt5
from PyQt5.QtWidgets import QApplication
cb = QApplication.clipboard()
if cb.mimeData().hasImage():
qt_img = cb.image()
pil_img = Image.fromqimage(qt_img)  # 转换为PIL图像
pil_img.save(path, "PNG")
6.2. GTK
import gtk
clipboard = gtk.clipboard_get()
image = clipboard.wait_for_image()
if image is not None:
getsavefilename
image.save(fname, "png")