如何将Flask服务器上创建的PIL映像下载到我的桌面。Image.save()仅将其保存到服务器。无法通过URL访问图像

2024-09-28 20:43:14 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我创建了一个PIL映像并将其保存到服务器。这将是好的,但我想避免保存这些图像到服务器,如果可能的话,而只是用户的桌面。我试图寻找下载文件的方法,但是几乎所有的方法都涉及url,这在我的情况下是不适用的

我的代码:

@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)

Tags: textimgalbumpositionitemswidthtwfont
2条回答

答复:

send_file(image, as_attachment=True)

具体来说,附件就是将文件下载到桌面的内容

我的意思是,我不知道如何将它保存到桌面上,但是你可以让他们下载它:

return send_from_directory(directory=folder, filename=filename)

其中directory是文件夹,filename是要发送的文件名

这可能意味着您必须先将其保存到文件中,因此可能有更好的方法来实现这一点

您可以使用此线程获取更多信息: Flask Download a File

相关问题 更多 >