Search code examples
pythonimageflaskpython-imaging-librarypythonanywhere

How to download a PIL Image created on a Flask server to my desktop. Image.save() only saves it to the server. Cant access the image by URL


So I create a PIL Image and it is saved to the server. This would be fine and dandy however I would like to avoid saving these images to the server if possible and rather to just the user's desktop. I tried looking up ways to download files however almost all of them seem to involve a url, which is not applicable in my situation.

My code:

@app.route('/createAlbumStory', methods = ['GET'])
def create_album_story():
    album = scrapeAlbumDB()
    albumDict = json.loads(album)
    items = albumDict
    user = str(session['username']) + "_createdAlbumStory.jpeg"
    width, height = (1080, 1920)
    img = Image.new('RGB', (width, height), (33, 33, 33))
    draw = ImageDraw.Draw(img)
    # font = ImageFont.truetype(<font-file>, <font-size>)
    font = ImageFont.truetype("/home/Spotify365/mysite/GothamBold.ttf", 50)
    fontB = ImageFont.truetype("/home/Spotify365/mysite/GothamBold.ttf", 30)
    # topText = str(session['username']) + "'s Top 5 Played Albums"
    topText = "user's Top 5 Played Albums"
    tW, tH = draw.textsize(topText, font)
    draw.text(((width - tW)/2, 100), topText ,(255, 255, 255),font)
    # NEED TO CHECK IF THIS LOCAL TRACK IF SO SHIFT TO NEXT ARTIST
    # img.paste(topSongImage, (340, 250))
    for i in range(0, 5):
        topSongImage = Image.open(urllib.request.urlopen(items[i][1][1]))
        topSongImage = topSongImage.resize((200, 200))
        img.paste(topSongImage, (100, 250 + (i * 300) - 50))
        draw.rectangle(((325, 200 + (i * 300)), (975, 400 + (i * 300))), fill="white")
        songText = str(items[i][0][0]) + "-" + str(items[i][0][1])
        position = (350, 300 + (i * 300) - 50)
        draw.text(position, songText, (0, 0, 0), fontB)
        timeText = str(convert(items[i][1][0]))
        position = (350, 375 + (i * 300) - 50)
        draw.text(position, timeText, (0, 0, 0), fontB)
    adText = "Generated by Spotify365"
    tW, tH = draw.textsize(adText, font)
    draw.text(((width - tW)/2, 1670), adText ,(255, 255, 255),font)
    userText = "@spotify_365"
    tW, tH = draw.textsize(userText, font)
    # draw.text(((width - tW)/2, 1820), userText ,(255, 255, 255),font)
    img.save(user)
    return str(user)

Solution

  • I mean, i don't know about saving it to the desktop, however you could definitely make them download it:

    return send_from_directory(directory=folder, filename=filename)
    

    Where the directory is the folder, and filename is the name of the file you are sending

    This would probably mean that you would have to save it to file first though, so there may be a better way to do this.

    You can use this thread for more info: Flask Download a File