Niansuh commited on
Commit
4072732
·
verified ·
1 Parent(s): 0c2c873

Create image.py

Browse files
Files changed (1) hide show
  1. image.py +66 -0
image.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/image.py
2
+
3
+ import re
4
+ from io import BytesIO
5
+ import base64
6
+ from typing import Union
7
+
8
+ from .typing import ImageType
9
+
10
+ try:
11
+ from PIL import Image
12
+ except ImportError:
13
+ Image = None # Handle absence of PIL
14
+
15
+ from .errors import MissingRequirementsError
16
+
17
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'}
18
+
19
+ def is_allowed_extension(filename: str) -> bool:
20
+ """
21
+ Checks if the given filename has an allowed extension.
22
+ """
23
+ return '.' in filename and \
24
+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
25
+
26
+ def is_data_uri_an_image(data_uri: str) -> bool:
27
+ """
28
+ Checks if the given data URI represents an image.
29
+ """
30
+ if not re.match(r'data:image/(\w+);base64,', data_uri):
31
+ raise ValueError("Invalid data URI image.")
32
+ image_format = re.match(r'data:image/(\w+);base64,', data_uri).group(1).lower()
33
+ if image_format not in ALLOWED_EXTENSIONS and image_format != "svg+xml":
34
+ raise ValueError("Invalid image format (from MIME type).")
35
+ return True
36
+
37
+ def extract_data_uri(data_uri: str) -> bytes:
38
+ """
39
+ Extracts the binary data from the given data URI.
40
+ """
41
+ data = data_uri.split(",")[1]
42
+ return base64.b64decode(data)
43
+
44
+ def to_data_uri(image: str) -> str:
45
+ """
46
+ Validates and returns the data URI for an image.
47
+ """
48
+ is_data_uri_an_image(image)
49
+ return image
50
+
51
+ def to_image(image: str) -> ImageType:
52
+ """
53
+ Converts a base64-encoded image to bytes.
54
+ """
55
+ if Image is None:
56
+ raise MissingRequirementsError('Install "pillow" package for image processing.')
57
+ is_data_uri_an_image(image)
58
+ return extract_data_uri(image)
59
+
60
+ class MissingRequirementsError(Exception):
61
+ pass
62
+
63
+ class ImageResponse:
64
+ def __init__(self, url: str, alt: str):
65
+ self.url = url
66
+ self.alt = alt