Ask Your Question
4

How can Pillow and Django be used to download an image?

asked 2023-05-15 02:28:09 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-15 02:40:01 +0000

djk gravatar image
  1. Import the necessary modules:
from django.shortcuts import HttpResponse
from PIL import Image
from io import BytesIO
import requests
  1. Define a view function that reads the image data from a URL and returns it as an HTTP response:
def download_image(request):
    response = requests.get('https://example.com/image.jpg')
    image = Image.open(BytesIO(response.content))
    response = HttpResponse(content_type='image/jpeg')
    image.save(response, 'JPEG')
    response['Content-Disposition'] = 'attachment; filename="image.jpg"'
    return response
  1. In your Django application's URL configuration, specify a URL pattern that maps to the download_image view function:
from django.urls import path
from . import views

urlpatterns = [
    path('download-image/', views.download_image, name='download_image'),
]
  1. In your HTML template, create a link or button that points to the download-image URL:
<a href="{% url 'download_image' %}">Download Image</a>

When the user clicks the link, the download_image function is executed, fetching the image from the specified URL and returning it as a downloadable file named "image.jpg".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-15 02:28:09 +0000

Seen: 16 times

Last updated: May 15 '23