2018~/Python Skill Up
8. pillow : 이미지 패키지(2) - ImageGrab 모듈과 Image 클래스
반원_SemiCircle
2019. 9. 6. 10:27
ImageGrab 모듈
- 레퍼런스 문서 : 링크
pillow 패키지의 ImageGrab.py 소스코드
from . import Image
import sys
if sys.platform == "win32":
grabber = Image.core.grabscreen
elif sys.platform == "darwin":
import os
import tempfile
import subprocess
else:
raise ImportError("ImageGrab is macOS and Windows only")
def grab(bbox=None, include_layered_windows=False):
if sys.platform == "darwin":
fh, filepath = tempfile.mkstemp(".png")
os.close(fh)
subprocess.call(["screencapture", "-x", filepath])
im = Image.open(filepath)
im.load()
os.unlink(filepath)
else:
size, data = grabber(include_layered_windows)
im = Image.frombytes(
"RGB",
size,
data,
# RGB, 32-bit line padding, origin lower left corner
"raw",
"BGR",
(size[0] * 3 + 3) & -4,
-1,
)
if bbox:
im = im.crop(bbox)
return im
def grabclipboard():
if sys.platform == "darwin":
fh, filepath = tempfile.mkstemp(".jpg")
os.close(fh)
commands = [
'set theFile to (open for access POSIX file "'
+ filepath
+ '" with write permission)',
"try",
" write (the clipboard as JPEG picture) to theFile",
"end try",
"close access theFile",
]
script = ["osascript"]
for command in commands:
script += ["-e", command]
subprocess.call(script)
im = None
if os.stat(filepath).st_size != 0:
im = Image.open(filepath)
im.load()
os.unlink(filepath)
return im
else:
data = Image.core.grabclipboard()
if isinstance(data, bytes):
from . import BmpImagePlugin
import io
return BmpImagePlugin.DibImageFile(io.BytesIO(data))
return data
기본 예제 - grab
import pyautogui as pg
from PIL import ImageGrab, Image
# 화면 사이즈
w_size = pg.size()
# 우상단 그림을 캡처 - 임시로 파일 저장됨
img = ImageGrab.grab((w_size[0]-200,0,w_size[0],200)) # x1,y1,x2,y2
img.save('./test.png') # 그림 저장
img.show() # 그림 열기
Image모듈의 Image 클래스
- pillow 패키지에서는 모든 그림 파일을 Image 클래스를 이용하여 관리한다.
- 레퍼런스 참고 :링크
기본 예제 - rotate
- 기타 예제는 다음을 참고 링크
from PIL import Image im = Image.open("bride.jpg") im.rotate(45).show()