Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
clipboard.py 2.30 KB
Copy Edit Raw Blame History
yyt authored 2024-05-12 10:18 . 整理依赖
import base64
import io
import os
import pyperclip
import win32con
from win32clipboard import OpenClipboard, GetClipboardData, CloseClipboard, IsClipboardFormatAvailable
from PIL import ImageGrab
from enum import Enum
class ClipboardType(Enum):
TEXT = 'text'
IMG = 'img'
FILE = 'file'
class ClipboardUtil:
@staticmethod
def get_content(con) -> tuple[bool, any]:
"""
获取剪贴板内容
:param con: win32con.xxx
:return: 是否成功, 剪贴板内容|异常对象
"""
if not IsClipboardFormatAvailable(con):
return False, None
OpenClipboard()
try:
res = GetClipboardData(con)
except Exception as e:
return False, e
finally:
CloseClipboard()
return True, res
@staticmethod
def get_files() -> tuple[bool, any]:
"""
获取剪贴板的文件
:return: 是否成功, 剪贴板内容|异常对象
"""
success, res = ClipboardUtil.get_content(win32con.CF_HDROP)
if not success:
return False, res
file_path_list = [file for file in res if os.path.exists(file) and not os.path.isdir(file)]
return True, file_path_list
@staticmethod
def get_text() -> tuple[bool, any]:
"""
获取剪贴板的文本
:return: 是否成功, 剪贴板内容|异常对象
"""
return ClipboardUtil.get_content(win32con.CF_UNICODETEXT)
@staticmethod
def set_text(text: str) -> tuple[bool, any]:
"""
设置剪贴板的文本
:return: 是否成功, 异常对象|None
"""
try:
pyperclip.copy(text)
except Exception as e:
return False, str(e)
return True, None
@staticmethod
def get_img_base64() -> tuple[bool, str]:
"""
获取剪贴板的图片,并转换为base64编码
:return: 是否成功, 图片的base64编码|错误文本
"""
img = ImageGrab.grabclipboard()
if not img:
return False, '未复制图像'
output_buffer = io.BytesIO()
img.save(output_buffer, format='PNG')
img_bytes = output_buffer.getvalue()
base64_str = base64.b64encode(img_bytes).decode('utf-8')
return True, base64_str
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化