从剪贴板压缩图像

Compress images from clipboard

提问人:tsy 提问时间:11/1/2023 更新时间:11/1/2023 访问量:35

问:

我想从剪贴板压缩图像并将它们放回原处,但是当我将它们转换为bmp格式时,图像的大小会增加。

def set_clipboard_image(img_str):
    bmp_data = zlib.decompress(base64.b64decode(img_str))
    image = Image.open(io.BytesIO(bmp_data))
    output = BytesIO()
    image.convert("RGB").save(output, "BMP")
    bmp_data = output.getvalue()[14:]
    
    success = False
    while not success:
        try:
            win32clipboard.OpenClipboard()
            win32clipboard.EmptyClipboard()
            win32clipboard.SetClipboardData(win32clipboard.CF_DIB, bmp_data)
            win32clipboard.CloseClipboard()
            success = True
        except Exception as e:
            print(f"Error: {e}. Retrying...")
            time.sleep(0.1)

所以这个

    cropped_image.save(buffer, format="JPEG", quality = 55)
    img_str = base64.b64encode(zlib.compress(buffer.getvalue(), 9)).decode('utf-8')

略微减小了图像的大小,但将其转换为 BMP 格式会将其增加许多倍,从而导致图像比以前大得多。如何解决?

代码的其余部分:

def process_image(image):
    global counter
    width, height = image.size
    cropped_image = image.crop((0, 0, width - 5, height - 5))
    current_time = datetime.now().strftime('%H:%M:%S')
    print(f"[green]{counter}. [{current_time}][/green][yellow] {width}x{height}[/yellow] -> [green]{width - 5}x{height - 5}[/green]")
    buffer = io.BytesIO()
    cropped_image.save(buffer, format="JPEG", quality = 55)
    img_str = base64.b64encode(zlib.compress(buffer.getvalue(), 9)).decode('utf-8')
    counter += 1
    return img_str

def get_clipboard_image():
    success = False
    data = None
    while not success:
        try:
            win32clipboard.OpenClipboard()
            if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
                data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
            elif win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT):
                data = None
            win32clipboard.CloseClipboard()
            success = True
        except Exception as e:
            print(f"Error: {e}. Retrying...")
            time.sleep(0.1)

    return data

prev_image = None

while True:
    try:
        curr_data = get_clipboard_image()
        if curr_data is not None:
            curr_image = Image.open(BytesIO(curr_data))
            if prev_image is None or list(curr_image.getdata()) != list(prev_image.getdata()):
                img_str = process_image(curr_image)
                set_clipboard_image(img_str)
                prev_image = Image.open(io.BytesIO(zlib.decompress(base64.b64decode(img_str))))

        time.sleep(0.5)
        
    except KeyboardInterrupt:
        break

python 图像 文件 压缩 剪贴板

评论

0赞 Dan Mašek 11/1/2023
“将 [质量 55 JPEG] 转换为 bmp 格式会使 [文件大小] 增加很多倍”——这并不奇怪。似乎您需要修复对这两种图像格式的理解,而不是代码。

答: 暂无答案