컴퓨터/Python

[Python] 파이썬, 윈도우 화면에 이미지 그리기

sjblog 2024. 4. 22. 09:27
반응형

1. 이미지 그리기

import win32gui
from PIL import Image, ImageWin

class DrawOnDesktop:
    def __init__(self):
        self.hwnd = win32gui.GetDesktopWindow()
        self.hdc = win32gui.GetDC(self.hwnd)

    def draw_image(self, image_path, x, y):
        # 이미지 열기
        image = Image.open(image_path)

        # 이미지를 바탕화면의 DC에 복사
        img_dc = ImageWin.Dib(image)
        img_dc.draw(self.hdc, (x, y, x + image.width, y + image.height))

# 이미지 파일 경로 (.jpg 이미지)
image_path = "test.png"

# 이미지를 바탕화면의 특정 위치에 그리기
DrawOnDesktop().draw_image(image_path, 100, 100)

 

2. 결과

(100, 100) 위치에 test.png 이미지를 윈도우 화면에 그릴 수 있습니다.

 
이미지는 바탕화면의 해당 영역에 새로운 이벤트가 발생하면 사라집니다.
 
윈도우에서는 화면을 다시 그리는 이벤트가 발생할 때 바탕화면을 새로 그리기 때문이죠.
 

3. 계속 떠 있게 하고 싶다.

이미지가 사라지지 않게 하고 싶다면 간단하게 반복문을 사용하면 됩니다.

import win32gui
from PIL import Image, ImageWin
import time

class DrawOnDesktop:
    def __init__(self):
        self.hwnd = win32gui.GetDesktopWindow()
        self.hdc = win32gui.GetDC(self.hwnd)

    def draw_image(self, image_path, x, y):
        # 이미지 열기
        image = Image.open(image_path)

        # 이미지를 바탕화면의 DC에 복사
        img_dc = ImageWin.Dib(image)
        img_dc.draw(self.hdc, (x, y, x + image.width, y + image.height))

# 이미지 파일 경로 (.jpg 이미지)
image_path = "test.png"

# 이미지를 바탕화면의 특정 위치에 반복해서 그리기
drawing = DrawOnDesktop()

while True:
    drawing.draw_image(image_path, 100, 100)
    time.sleep(0.005)

 

4. 네모 그리기

class DrawOnDesktop:
    def __init__(self):
        self.hwnd = win32gui.GetDesktopWindow()
        self.hdc = win32gui.GetDC(self.hwnd)
        
	def draw_rect(self, x, y, w, h):
    	# 색 지정
   		color = win32api.RGB(255, 0, 0) # 빨강
    
    	# 가로 직선
    	for i in range(x, x + w):
        	win32gui.SetPixel(self.hdc, i, y, color)
        	win32gui.SetPixel(self.hdc, i, y + h, color)
    
    	# 세로 직선
    	for i in range(y, y + h):
        	win32gui.SetPixel(self.hdc, x, i, color)
        	win32gui.SetPixel(self.hdc, x + w, i, color)

# 바탕화면의 특정 위치에 네모 그리기
DrawOnDesktop().draw_rect(100, 100, 50, 50)
반응형