Skip to content

Commit e6cdede

Browse files
committed
Adding view to display image as png for sharing
1 parent 547dac2 commit e6cdede

2 files changed

Lines changed: 26 additions & 7 deletions

File tree

images/views.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1+
import base64
2+
import uuid
3+
14
from django.contrib import messages
25
from django.contrib.auth.decorators import login_required
3-
from django.http import HttpResponseBadRequest, JsonResponse, HttpResponse
4-
from django.shortcuts import render, redirect
5-
from django.core.files.images import ImageFile
6-
from django.core.files.base import ContentFile
6+
from django.http import HttpResponseBadRequest, HttpResponse, \
7+
Http404
8+
from django.shortcuts import get_object_or_404, redirect
79

810
from .helpers import image_to_base64str
911
from accounts.models import CustomUser
1012
from hackathon.models import HackTeam, HackProject, Hackathon
13+
from showcase.models import Showcase
1114

1215
VALID_UPLOAD_TYPES = ['profile_image', 'header_image', 'project_image',
1316
'screenshot', 'hackathon_image',
@@ -31,7 +34,7 @@ def save_image(request):
3134
if upload_type not in VALID_UPLOAD_TYPES:
3235
messages.error(request, 'Wrong upload type used.')
3336
return redirect(request.META.get('HTTP_REFERER'))
34-
37+
3538
if upload_type == 'profile_image':
3639
user = CustomUser.objects.get(id=request.user.id)
3740
user.profile_image = image_to_base64str(upload_file)
@@ -55,8 +58,21 @@ def save_image(request):
5558

5659
messages.success(request, 'Image uploaded successfully.')
5760
return redirect(request.META.get('HTTP_REFERER'))
58-
61+
5962
else:
6063
return HttpResponseBadRequest()
61-
return redirect(request.META.get('HTTP_REFERER'))
6264

65+
66+
@login_required
67+
def render_image(request, showcase_id, image_hash):
68+
try:
69+
image_hash_uuid = uuid.UUID(image_hash)
70+
showcase = get_object_or_404(Showcase, hash=image_hash_uuid)
71+
if showcase.showcase_image:
72+
data_uri = showcase.showcase_image
73+
image_data = data_uri.partition('base64,')[2]
74+
binary = base64.b64decode(image_data)
75+
return HttpResponse(binary, content_type='image/png')
76+
except ValueError:
77+
raise Http404()
78+
raise Http404()

showcase/urls.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
from django.urls import path
22
from .views import view_showcases, view_showcase
3+
from images.views import render_image
34

45
urlpatterns = [
56
path("", view_showcases, name="view_showcases"),
67
path("<int:showcase_id>/", view_showcase, name="view_showcase"),
8+
path("<int:showcase_id>/image/<str:image_hash>/", render_image,
9+
name="render_showcase_image"),
710
]

0 commit comments

Comments
 (0)