【问题标题】:How to convert an uploaded file (InMemoryUploadedFile) from pdf to jpeg in Django using wand?如何使用 wand 在 Django 中将上传的文件(InMemoryUploadedFile)从 pdf 转换为 jpeg?
【发布时间】:2019-12-08 07:05:26
【问题描述】:

我正在尝试将在 Django 中上传的 pdf 文件转换为 jpg 文件。我想直接在 InMemoryUploadedFile 状态下使用文件。

我尝试使用魔杖,但没有成功。 这是我写的代码:

from django.shortcuts import render
from wand.image import Image as wi

# Create your views here.
def readPDF(request):
    context = {}
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        if uploaded_file.content_type == 'application/pdf':
            pdf = wi(filename=uploaded_file.name, resolution=300)
            pdfImage = pdf.convert("jpeg")
    return render(request, 'readPDF.html', {"pdf": pdfImage})

我尝试了不同的方法,例如使用uploaded_file.file 或uploaded_file.name 作为魔杖图像的第一个参数,但没有任何成功。`

提前感谢您的帮助!

【问题讨论】:

    标签: django python-3.x file-upload type-conversion wand


    【解决方案1】:

    应该能够将InMemoryUploadedFile 直接传递给Wand 的构造函数。

    uploaded_file = request.FILES['document']
    if uploaded_file.content_type == 'application/pdf':
        with wi(file=uploaded_file, resolution=300) as pdf:
            # ...
    

    但是,我不建议尝试在 HTTP 请求中将 PDF 页面转换为 JPEG。最好将文档写入存储,并让后台工作人员管理缓慢/不安全的任务。

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多