python截图、压缩、转base64,可以用2m压缩到100k,肉眼不失真

import win32gui
import win32ui
import win32con
import numpy as np
import cv2
import base64

# 通过句柄截取窗口内容
def capture_window_by_handle(handle):
    left, top, right, bottom = win32gui.GetWindowRect(handle)
    width = right - left
    height = bottom - top

    hwnd_dc = win32gui.GetWindowDC(handle)
    mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)

    save_dc = mfc_dc.CreateCompatibleDC()
    save_bitmap = win32ui.CreateBitmap()
    save_bitmap.CreateCompatibleBitmap(mfc_dc, width, height)
    save_dc.SelectObject(save_bitmap)

    result = save_dc.BitBlt((0, 0), (width, height), mfc_dc, (0, 0), win32con.SRCCOPY)

    bmp_info = save_bitmap.GetInfo()
    bmp_str = save_bitmap.GetBitmapBits(True)

    # 从缓冲区创建NumPy数组
    image = np.frombuffer(bmp_str, dtype=np.uint8)
    image = image.reshape((height, width, 4))  # RGBA格式

    save_dc.DeleteDC()
    mfc_dc.DeleteDC()
    win32gui.ReleaseDC(handle, hwnd_dc)
    win32gui.DeleteObject(save_bitmap.GetHandle())

    return image

# 压缩图像函数
def pic_compress(img_cv, target_size=199, quality=100, step=5):
    img_byte = cv2.imencode('.jpg', img_cv, [int(cv2.IMWRITE_JPEG_QUALITY), quality])[1]
    current_size = len(img_byte) / 1024
    while current_size > target_size:
        img_byte = cv2.imencode('.jpg', img_cv, [int(cv2.IMWRITE_JPEG_QUALITY), quality])[1]
        if quality - step < 0:
            break
        quality -= step
        current_size = len(img_byte) / 1024
    return img_byte

def main():
    # 通过句柄获取窗口
    target_handle = win32gui.FindWindow(None, "地下城与勇士:创新世纪")  # 替换为目标窗口的标题

    if target_handle == 0:
        print("未找到目标窗口")
        return

    # 截取窗口内容
    captured_image = capture_window_by_handle(target_handle)

    # 保存截图到本地
    # original_save_path = "01original_captured_image.png"
    # cv2.imwrite(original_save_path, captured_image)
    # print("原始截图已保存到:", original_save_path)

    # 将图像转换为OpenCV格式(BGR)
    cv2_captured_image = cv2.cvtColor(captured_image, cv2.COLOR_RGBA2BGR)

    # 压缩图像
    compressed_image_byte = pic_compress(captured_image, target_size=100)

    # 保存压缩后的图像到本地
    compressed_save_path = "01compressed_captured_image.jpg"
    with open(compressed_save_path, 'wb') as f:
        f.write(compressed_image_byte)
    print("压缩后的图像已保存到:", compressed_save_path)

    # 将压缩后的图像转为base64
    compressed_image_base64 = base64.b64encode(compressed_image_byte).decode('utf-8')
    print("压缩后的图像base64编码:", compressed_image_base64)

if __name__ == '__main__':
    while True:
        import time
        t1 = time.time()
        main()
        t2 = time.time()
        print(t2-t1)

 

posted @ 2023-08-22 21:03  zwnsyw  阅读(216)  评论(0编辑  收藏  举报