本文整理匯總了Python中django.utils.image.Image類的典型用法代碼示例。如果您正苦於以下問題:Python Image類的具體用法?Python Image怎麽用?Python Image使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Image類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: to_python
def to_python(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).
"""
f = super(ImageField, self).to_python(data)
if f is None:
return None
from django.utils.image import Image
# We need to get a file object for Pillow. We might have a path or we might
# have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
file = BytesIO(data.read())
else:
file = BytesIO(data['content'])
try:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
Image.open(file).verify()
except Exception:
# Pillow (or PIL) doesn't recognize it as an image.
six.reraise(ValidationError, ValidationError(self.error_messages['invalid_image']), sys.exc_info()[2])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f
示例2: is_image
def is_image(self):
# taken from ImageField
try:
Image.open(self.data).verify()
return True
except Exception:
return False
示例3: create_imagefile
def create_imagefile(self):
"""Creates a PNG image with StringIO"""
img = Image.new("RGBA", size=(200, 200), color=(255, 0, 0, 0))
file_object = StringIO.StringIO()
img.save(file_object, 'png')
file_object.seek(0)
return file_object
示例4: clean_image
def clean_image(self):
image = self.cleaned_data["image"]
if Image.open(image).format.lower() not in settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT:
raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
% ", ".join(settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT)))
image.seek(0)
return image
示例5: test_bug_19457
def test_bug_19457(self):
"""
Regression test for #19457
get_image_dimensions fails on some pngs, while Image.size is working good on them
"""
img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
try:
size = get_image_dimensions(img_path)
except zlib.error:
self.fail("Exception raised from get_image_dimensions().")
self.assertEqual(size, Image.open(img_path).size)
示例6: test_multiple_calls
def test_multiple_calls(self):
"""
Multiple calls of get_image_dimensions() should return the same size.
"""
from django.core.files.images import ImageFile
img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
image = ImageFile(open(img_path, 'rb'))
image_pil = Image.open(img_path)
size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
self.assertEqual(image_pil.size, size_1)
self.assertEqual(size_1, size_2)
示例7: test_multiple_calls
def test_multiple_calls(self):
"""
Multiple calls of get_image_dimensions() should return the same size.
"""
img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
with open(img_path, 'rb') as fh:
image = images.ImageFile(fh)
image_pil = Image.open(fh)
size_1 = images.get_image_dimensions(image)
size_2 = images.get_image_dimensions(image)
self.assertEqual(image_pil.size, size_1)
self.assertEqual(size_1, size_2)
示例8: from_url
def from_url(creator, url):
try:
return Cover.objects.get(original_url=url)
except Cover.DoesNotExist:
pass
img_temp = None
try:
cover = Cover(creator=creator, create_date=datetime.now(), original_url=url)
response = urllib.request.urlopen(url)
if 'content-length' not in response.headers or int(response.headers['content-length']) > 1000000:
return None
data = response.read()
Image.open(BytesIO(data)).verify()
img = Image.open(BytesIO(data))
img = img.resize((150, 150), Image.ANTIALIAS)
img_temp = NamedTemporaryFile(delete=True)
ext = url.split('.')[-1].upper()
if ext == 'JPG':
ext = 'JPEG'
img.save(img_temp, format=ext)
cover.file.save(f(None, url), File(img_temp), save=True)
return cover
except:
return None
finally:
if img_temp:
img_temp.close()
示例9: test_signal_catches_create
def test_signal_catches_create(self):
"""db_action signal should catch creation of any model entry"""
# some foreign model such as auth.user
user = User.objects.create_user("dumb", "[email protected]", "user")
self.assertEqual(self.dbaction_count + 1, DbAction.objects.count())
img = Image.new("RGBA", size=(200, 200), color=(255, 0, 0, 0))
temp_handle = StringIO.StringIO()
img.save(temp_handle, 'png')
temp_handle.seek(0)
# some local model
Profile.objects.create(user=user, birth_date=datetime.date.today(),
bio="bio", contacts="contacts",
jabber="jab", skype="sky",
photo=ContentFile(temp_handle.read()))
self.assertEqual(self.dbaction_count + 2, DbAction.objects.count())
示例10: students_add
def students_add(request):
form = StudentAddForm(request.POST or None)
context = {'form': form}
context.update({'page_title': _(u"Add Student")})
# was form posted?
if request.method == "POST":
# was form add button clicked?
if request.POST.get('add_button') is not None:
# error collection
errors = OrderedDict()
# validate student data will go here
data = {'middle_name': request.POST.get('middle_name'),
'notes': request.POST.get('notes')}
# validate user input
first_name = request.POST.get('first_name', '').strip()
if not first_name:
errors['first_name'] = _(u"First Name field is required")
else:
data['first_name'] = first_name
last_name = request.POST.get('last_name', '').strip()
if not last_name:
errors['last_name'] = _(u"Last Name field is required")
else:
data['last_name'] = last_name
birthday = request.POST.get('birthday', '').strip()
if not birthday:
errors['birthday'] = _(u"Birthday date is required")
else:
data['birthday'] = birthday
try:
datetime.strptime(birthday, '%Y-%m-%d')
except Exception:
errors['birthday'] = _(u"Please, enter the correct date (Ex. 1984-12-30)")
else:
data['birthday'] = birthday
ticket = request.POST.get('ticket', '').strip()
if not ticket:
errors['ticket'] = _(u"Ticket number is required")
else:
data['ticket'] = ticket
student_group = request.POST.get('student_group', '').strip()
if not student_group:
errors['student_group'] = _(u"Select group for student")
else:
groups = Group.objects.filter(pk=student_group)
if len(groups) != 1:
errors['student_group'] = _(u"Select group for student")
else:
data['student_group'] = Group.objects.get(pk=student_group)
photo = request.FILES.get('photo')
if photo:
if photo.size > (2*1024*1024):
errors['photo'] = _(u'The file is too big. Must be less then 2MB')
else:
try:
Image.open(photo).verify()
except Exception:
errors['photo'] = _(u"File is not an image")
else:
data['photo'] = photo
if not errors:
# create student object
student = Student(**data)
# save it to database
student.save()
# redirect user to students list
messages.info(
request,
_(u'Student "%(first_name)s %(last_name)s" sucessfully added!') %
{'first_name': student.first_name, 'last_name': student.last_name},
)
return HttpResponseRedirect(reverse('home'))
else:
# render form with errors and previous user input
for error_key in errors.keys():
messages.error(request, errors[error_key])
context['errors'] = errors
return render(request, 'students/students_add.html',
context)
elif request.POST.get('cancel_button') is not None:
# redirect to home page on cancel button
messages.info(
request,
_(u'Adding a student got canceled!'),
)
return HttpResponseRedirect(reverse('home'))
else:
# initial form render
return render(request, 'students/students_add.html',
context)