[英]Cannot identify image file PIL
我正在使用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
我認為您需要將文件保存在某處。 目前,您正在將內存文件設置為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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.