Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get_image api added #672

Merged
merged 6 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,14 @@ Or, for a local file:
"path_url": "/path/to/local/image.gif"
}

Windows example

.. code-block:: json

{
"path_url": "C:\\path\\to\\local\\image.gif"
}

Sample Response
^^^^^^^^^^^^^^^

Expand All @@ -413,6 +421,100 @@ A successful response with two extracted frames might look like this:
]
}

/api/get_image
===========================================

Overview
--------

A RESTful endpoint designed for retrieving an image. Clients can request a file by providing either the URL or the local file path of the image resource. The image is returned in JPEG format for efficient data transmission.

Endpoint Details
----------------

- **Endpoint Path**: ``/api/get_image``

Request
-------

- **Method**: GET
- **Request Data**:
- ``path_url`` (String): The URL or local file path of the image from to be opened.

Response
--------

- **Success**:

- Status Code: 200

- Body:

- ``image`` (String): A base64 encoded image in JPEG format.

- **Failure**:

- Status Code: 400 (Bad Request)

- When JSON decoding fails or the required attribute ``path_url`` is not provided.

- Status Code: 404 (Not Found)

- When the image at the specified URL or file path cannot be opened or processed.

Error Handling
--------------

In case of an error, the endpoint returns a JSON object with the following structure:

.. code-block:: json

{
"status": "failed",
"reason": "<error reason>"
}

Usage Example
-------------

Requesting Image
^^^^^^^^^^^^^^^^^^^^^

To request an image, send a GET request with either the URL or local file path in the request data:

.. code-block:: json

{
"path_url": "http://example.com/image.gif"
}

Or, for a local file:

.. code-block:: json

{
"path_url": "/path/to/local/image.gif"
}

Windows example

.. code-block:: json

{
"path_url": "C:\\path\\to\\local\\image.gif"
}

Sample Response
^^^^^^^^^^^^^^^

A successful response with image data might look like this:

.. code-block:: json

{
"image": "<base64-encoded JPEG data>"
}

/api/effects
=========================

Expand Down
8 changes: 6 additions & 2 deletions ledfx/api/get_gif_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ async def get(self, request: web.Request) -> web.Response:
)
frames.append(encoded_frame)

response = {"frame_count": len(frames), "frames": frames}
response = {
"status": "success",
"frame_count": len(frames),
"frames": frames,
}

return web.json_response(data=response, status=200)
return await self.bare_request_success(response)
59 changes: 59 additions & 0 deletions ledfx/api/get_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import io
import logging
from json import JSONDecodeError

import pybase64
from aiohttp import web

from ledfx.api import RestEndpoint
from ledfx.utils import open_image

_LOGGER = logging.getLogger(__name__)


class GetImageEndpoint(RestEndpoint):
ENDPOINT_PATH = "/api/get_image"

async def get(self, request: web.Request) -> web.Response:
"""Open image and return as base64 encoded string

Args:
request (web.Request): The request object containing the `path_url` to open.

Returns:
web.Response: The HTTP response object containing the base64 encoded image.
"""
try:
data = await request.json()
except JSONDecodeError:
return await self.json_decode_error()

path_url = data.get("path_url")

if path_url is None:
return await self.invalid_request(
'Required attribute "path_url" was not provided'
)

_LOGGER.info(f"GetImageEndpoint from {path_url}")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved

image = open_image(path_url)

if not image:
return await self.invalid_request(
f"Failed to open GIF image from: {path_url}"
)

with io.BytesIO() as output:
# we don't care about a bit of loss, so encode to JPEG
# in example test 5x+ data saving 600kb - > 112 kb
image.convert("RGB").save(
output, format="JPEG"
) # Convert frame to JPEG
encoded_frame = pybase64.b64encode(output.getvalue()).decode(
"utf-8"
)

response = {"status": "success", "image": encoded_frame}

return await self.bare_request_success(response)
29 changes: 29 additions & 0 deletions ledfx/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,35 @@ def open_gif(gif_path):
return None


def open_image(image_path):
"""
Open an image from a local file or url

Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith(
"https://"
):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info("image downloaded and opened.")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return image

else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info("Image opened.")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return image
except Exception as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return None


def get_mono_font(size):
"""
Get a monospace font from a list of fonts common across platforms
Expand Down
Loading