File size: 1,784 Bytes
509a107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import mss
import mss.tools
from PIL import Image
import io
import numpy as np
from typing import Optional

class ScreenCapture:
    def __init__(self):
        self.sct = mss.mss()
    
    def capture(self, monitor_index: int = 0) -> bytes:
        try:
            if monitor_index == 0:
                monitor = self.sct.monitors[0]
            else:
                monitor = self.sct.monitors[monitor_index]
            
            screenshot = self.sct.grab(monitor)
            
            img = Image.frombytes(
                "RGB",
                (screenshot.width, screenshot.height),
                screenshot.rgb
            )
            
            img_byte_arr = io.BytesIO()
            img.save(img_byte_arr, format='PNG')
            img_byte_arr.seek(0)
            
            return img_byte_arr.getvalue()
            
        except Exception as e:
            print(f"Screen capture error: {e}")
            return self._create_placeholder_image()
    
    def create_thumbnail(self, image_data: bytes, size: tuple = (320, 240)) -> bytes:
        try:
            img = Image.open(io.BytesIO(image_data))
            img.thumbnail(size, Image.Resampling.LANCZOS)
            
            thumb_byte_arr = io.BytesIO()
            img.save(thumb_byte_arr, format='PNG')
            thumb_byte_arr.seek(0)
            
            return thumb_byte_arr.getvalue()
            
        except Exception as e:
            print(f"Thumbnail creation error: {e}")
            return image_data
    
    def _create_placeholder_image(self) -> bytes:
        img = Image.new('RGB', (1920, 1080), color='gray')
        img_byte_arr = io.BytesIO()
        img.save(img_byte_arr, format='PNG')
        img_byte_arr.seek(0)
        return img_byte_arr.getvalue()