mac 上 Python 读写剪贴板图片、文字

一、使用 ImageGrab

只能读,只能是图片。

只能获取截图后的、或是网页上复制的图片内容,复制的图片文件不能获取。

from PIL import ImageGrab
img = ImageGrab.grabclipboard()
img.save('paste.png', 'PNG')

二、使用 NSPasteboard

可读可写,可以是字符串,可以是图片。

# 读剪切板数据的格式类型
data_type = pb.types()
print data_type

# 读剪切板字符串
if NSPasteboardTypeString in data_type:
    str = pb.dataForType_(NSPasteboardTypeString)
    print str

# 读剪切板的截图
if "public.png" in data_type:
    img = pb.dataForType_("public.png")

# 读剪切板复制的图片文件名
if NSPasteboardTypePNG in data_type:
    img = pb.dataForType_(NSPasteboardTypePNG)
    print img

# 读剪切板复制的图片文件路径 url
if "public.file-url" in data_type:
    img = pb.dataForType_("public.file-url")
    print img

pb.clearContents()

# 写字符串 1
a = NSString.stringWithString_("hello world")
newData = a.nsstring().dataUsingEncoding_(NSUTF8StringEncoding)
pb.setData_forType_(newData, NSStringPboardType)

# 写字符串 2
a = NSArray.arrayWithObject_("hello world")
pb.writeObjects_(a)

# 写图片 1
imgNsData = NSData.alloc().initWithBytes_length_(img_bytes.getvalue(), img_bytes.tell())
imgNsImage = NSImage.alloc().initWithData_(imgNsData)
array = NSArray.arrayWithObject_(imgNsImage)
pb.writeObjects_(array)

# 写图片 2
imgNsData = NSData.dataWithBytes_length_(img_bytes.getvalue(), img_bytes.tell())
同上

Apple 的说明
Python 上的接口说明

Apple 的方法到 Python 的方法转换规律:

setData(_:forType:) 
setData_forType_

init(bytes: UnsafeRawPointer?, length: Int)
initWithBytes_length_

三、使用 pyperclip、clipboard

可读可写,只能是字符串。

import pyperclip
# 写字符串
pyperclip.copy("hello gdeer")
# 读字符串
text = pyperclip.paste()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值