Last active
June 3, 2022 03:16
-
-
Save hieuhani/9700200806faded2ee95b6575fff48e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Django==4.0.5 | |
djangorestframework==3.13.1 | |
Pillow==9.1.1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from django.urls import path | |
from rest_framework.decorators import api_view | |
from PIL import Image | |
import io | |
@api_view(['GET']) | |
def serve_image(request): | |
params = request.query_params | |
# http://127.0.0.1:8000/images/?width=200 | |
width = params.get('width') | |
# read image file content | |
im = Image.open(r"./original.jpeg") | |
# get image format | |
image_format = im.format | |
# get image content type to response to the client | |
mimetype = im.get_format_mimetype() | |
# resize if a width parameter is specified | |
if width: | |
original_width, original_height = im.size | |
# to keep the image ratio | |
im = im.resize((int(width), int((int(width) * original_height) / original_width))) | |
# initialize empty bytes array | |
img_byte_arr = io.BytesIO() | |
im.save(img_byte_arr, format=image_format) | |
return HttpResponse(img_byte_arr.getvalue(), content_type=mimetype) | |
urlpatterns = [ | |
path('image/', serve_image), | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment