Skip to content

Commit

Permalink
Merge pull request OpenEPaperLink#136 from gil04/main
Browse files Browse the repository at this point in the history
Support Data URI in dlimg
  • Loading branch information
jonasniesner authored Apr 25, 2024
2 parents e5569cb + c2fb121 commit a8adc1d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
21 changes: 21 additions & 0 deletions custom_components/open_epaper_link/imagegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import shutil
import asyncio
import time
import base64
from .const import DOMAIN
from .util import get_image_folder, get_image_path
from PIL import Image, ImageDraw, ImageFont
Expand Down Expand Up @@ -224,6 +225,26 @@ def customimage(entity_id, service, hass):
if "http://" in url or "https://" in url:
response = requests.get(url)
imgdl = Image.open(io.BytesIO(response.content))
elif "data:" in url:
s = url[5:]
if not s or ',' not in s:
raise HomeAssistantError('invalid data url')
media_type, _, raw_data = s.partition(',')
is_base64_encoded = media_type.endswith(';base64')
if is_base64_encoded:
media_type = media_type[:-7]
missing_padding = '=' * (-len(raw_data) % 4)
if missing_padding:
raw_data += missing_padding
try:
data = base64.b64decode(raw_data)
except ValueError as exc:
raise HomeAssistantError('invalid base64 in data url') from exc
else:
# Note: unquote_to_bytes() does not raise exceptions for invalid
# or partial escapes, so there is no error handling here.
data = urllib.parse.unquote_to_bytes(raw_data)
imgdl = Image.open(io.BytesIO(data))
else:
imgdl = Image.open(url)

Expand Down
2 changes: 1 addition & 1 deletion docs/drawcustom/supported_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ Downloads an image from a URL and renders it.

#### Parameters:

- **url** (required) url of the image to download. Either the full http/https URL address for an externally accessible image, or locally stored image needs to be e.g. `url: /config/media/chuck-icon.jpg` if stored within a folder called `media` in your main config or homeassistant folder.
- **url** (required) url of the image to download. Either the full http/https URL address for an externally accessible image or Data URI like 'data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs' or locally stored image needs to be e.g. `url: /config/media/chuck-icon.jpg` if stored within a folder called `media` in your main config or homeassistant folder.
- **x** (required) e.g. 20
- **y** (required) e.g. 10
- **xsize** (required) e.g. x size the image is resized
Expand Down

0 comments on commit a8adc1d

Please sign in to comment.