【问题标题】:Cannot identify image file PIL无法识别图像文件 PIL
【发布时间】:2016-02-07 11:19:37
【问题描述】:

我正在使用 Python 3.4 和 Django 1.9.2。当我尝试通过 python 脚本处理我的图像时,它可以工作,但是当我尝试在 Django 中运行它时,我在我的 Django 视图中使用相同的函数得到“无法识别图像文件 PIL 错误”。可能是什么问题?

from django.shortcuts import render
from image.models import fva
from PIL import Image
from PIL import ImageStat
from PIL import ImageFilter
from math import log
import mysql.connector

def homepage(request):
   return render(request,'index.html',{})

def rootmeansquare( im_file ):
   im = Image.open(im_file).convert('L')
   stat = ImageStat.Stat(im)
   return stat.rms[0]


def upload(request):
   filename = request.FILES['search_field']
   rms=rootmeansquare(filename)
   return render(request,'index.html',{})     

这是错误信息:

OSError at /upload
cannot identify image file <InMemoryUploadedFile: IMG_20160120_105936.jpg (image/jpeg)>
Request Method: POST
Request URL:    http://127.0.0.1:8000/upload
Django Version: 1.9.2
Exception Type: OSError
Exception Value:   
cannot identify image file <InMemoryUploadedFile: IMG_20160120_105936.jpg (image/jpeg)>
Exception Location: C:\Python34\lib\site-packages\PIL\Image.py in open, line 2287
Python Executable:  C:\Python34\python.exe
Python Version: 3.4.4
Python Path:   
['F:\\showimages\\showimages',
 'C:\\Windows\\SYSTEM32\\python34.zip',
 'C:\\Python34\\DLLs',
 'C:\\Python34\\lib',
 'C:\\Python34',
 'C:\\Python34\\lib\\site-packages']
Server time:    Sun, 7 Feb 2016 16:45:23 -0800

【问题讨论】:

    标签: python django python-imaging-library


    【解决方案1】:

    我认为您需要将文件保存在某个地方。目前,您将内存文件设置为filename

    filename = request.FILES['search_field']
    

    但是在你的函数中你尝试打开文件:

    def rootmeansquare( im_file ):
        im = Image.open(im_file)
        stat = ImageStat.Stat(im)
        return stat.mean[0]
    

    我不确切知道您的视图/模型是如何设置的,但我尝试将图像保存到磁盘,并传递对该文件的引用。您可以使用这种方法:

    from django.core.files.temp import NamedTemporaryFile
    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(filename)
    img_temp.flush() 
    
    # call function, passing in temporary image file reference
    rootmeansquare(img_temp)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多