无法识别图像文件PIL

时间:2016-02-07 11:19:37

标签: python django python-imaging-library

我正在使用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

1 个答案:

答案 0 :(得分:0)

我认为您需要将文件保存到某处。目前,您将内存中文件设置为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)