本文整理汇总了Python中imagekit.lib.Image类的典型用法代码示例。如果您正苦于以下问题:Python Image类的具体用法?Python Image怎么用?Python Image使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Image类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process
def process(cls, image, fmt, obj=None):
"""Adds a watermark to an image."""
if image.mode != 'RGBA':
image = image.convert('RGBA')
pink = (255, 94, 200)
white = (255, 255, 255)
im_width, im_height = image.size
copyright = "Copyright \xa9 by the Artist and Burning Man"
overlay = Image.new('RGBA', image.size, (0,0,0,0))
draw = ImageDraw.Draw(overlay)
draw.rectangle((0, im_height - 20, im_width, im_height),
fill=(0,0,0,90))
draw.text((10, im_height - 15), copyright, fill=(255,255,255,90))
newimage = Image.new('RGB', (im_width, im_height + 50), white)
draw2 = ImageDraw.Draw(newimage)
draw2.text((10, im_height + 5),
"\xa9 All images are copyright in their respective year, by "
"both the ",
fill=pink)
draw2.text((10, im_height + 15),
"photographer and Burning Man. For publication or other use ",
fill=pink)
draw2.text((10, im_height + 25),
"requests, contact the photographer at the email provided and ",
fill=pink)
draw2.text((10, im_height + 35),
"[email protected] for written permission.", fill=pink)
comp = Image.composite(overlay, image, overlay)
newimage.paste(comp, (0,0))
return newimage, fmt
示例2: process
def process(self, img):
# Convert bgcolor string to RGB value.
background_color = ImageColor.getrgb(self.background_color)
# Handle palleted images.
img = img.convert('RGBA')
# Copy orignial image and flip the orientation.
reflection = img.copy().transpose(Image.FLIP_TOP_BOTTOM)
# Create a new image filled with the bgcolor the same size.
background = Image.new("RGBA", img.size, background_color)
# Calculate our alpha mask.
start = int(255 - (255 * self.opacity)) # The start of our gradient.
steps = int(255 * self.size) # The number of intermedite values.
increment = (255 - start) / float(steps)
mask = Image.new('L', (1, 255))
for y in range(255):
if y < steps:
val = int(y * increment + start)
else:
val = 255
mask.putpixel((0, y), val)
alpha_mask = mask.resize(img.size)
# Merge the reflection onto our background color using the alpha mask.
reflection = Image.composite(background, reflection, alpha_mask)
# Crop the reflection.
reflection_height = int(img.size[1] * self.size)
reflection = reflection.crop((0, 0, img.size[0], reflection_height))
# Create new image sized to hold both the original image and
# the reflection.
composite = Image.new("RGBA", (img.size[0], img.size[1] + reflection_height), background_color)
# Paste the orignal image and the reflection into the composite image.
composite.paste(img, (0, 0))
composite.paste(reflection, (0, img.size[1]))
# Return the image complete with reflection effect.
return composite
示例3: get_default_photo
def get_default_photo(self):
try:
return Photo.objects.filter(user_default=True)[0]
except IndexError:
user_fallback = "%s/photos/%s" % (settings.MEDIA_ROOT, "img_user_fallback.png")
try:
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
photo = Photo(user_default=True)
photo.save()
Photo.objects.filter(pk=photo.pk).update(image="photos/img_user_fallback.png")
photo = Photo.objects.get(pk=photo.pk)
fp.close()
return photo
except:
user_fallback = "%s/images/%s" % (settings.GLOBALS_STATIC_ROOT, "img_user_fallback.png")
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
fp2 = open(user_fallback, "r")
target_file = File(fp2)
name = "img_user_fallback.png"
photo = Photo(user_default=True)
photo.image.save(name, target_file, save=True)
fp.close()
fp2.close()
return photo
示例4: process
def process(self, image):
mask = Image.open(os.path.join(settings.STATIC_ROOT, 'img/avatar-mask.png'))
layer = Image.new('RGBA', image.size)
layer.paste(mask)
newImage = Image.composite(layer, image, layer)
return newImage
示例5: process
def process(self, img):
# get watermark
wm = self._get_watermark()
wm_size = wm.size
# print('wm', wm)
# print('wm.mode', wm.mode)
# from PIL.PngImagePlugin import PngImageFile
# from PIL.JpegImagePlugin import JpegImageFile
if self.scale:
if isinstance(self.scale, (int, float)) and self.scale != 1:
# L&X
# wm_size[0] *= self.scale
# wm_size[1] *= self.scale
wm_size = (wm_size[0] * self.scale, wm_size[1] * self.scale)
wm = wm.scale(wm_size)
elif self.scale == True:
# from .resize import ResizeToFit
from imagekit.processors import ResizeToFit
wm = ResizeToFit(width=img.size[0], height=img.size[1],
upscale=True).process(wm)
wm_size = wm.size
# prepare image for overlaying (ensure alpha channel)
if img.mode != 'RGBA':
img = img.convert('RGBA')
# create a layer to place the watermark
layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
coords = _process_coords(img.size, wm_size, self.position)
print('L&X', 'wm', wm)
print('L&X', 'wm.size', wm.size)
print('L&X', 'coords', coords)
coords = (int(coords[0]), int(coords[1]))
if self.repeat:
sx = coords[0] % wm_size[0] - wm_size[0]
sy = coords[1] % wm_size[1] - wm_size[1]
for x in range(sx, img.size[0], wm_size[0]):
for y in range(sy, img.size[1], wm_size[1]):
layer.paste(wm, (x, y))
else:
layer.paste(wm, coords)
if self.opacity < 1:
alpha = layer.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity)
layer.putalpha(alpha)
# merge watermark layer
img = Image.composite(layer, img, layer)
return img
示例6: set_watermark
def set_watermark(image):
watermark = Archive.objects.get(id=51)
watermark = Image.open(watermark.archive)
image = Image.open(image)
scaled = ImageWatermark(watermark, position=("center", "center"), scale=True, opacity=1)
img_scaled = scaled.process(image)
return img_scaled
示例7: get_watermark
def get_watermark(self):
# open the image despite the format that the user provided for it
if self.watermark:
return self.watermark
if self.watermark_image:
return self.watermark_image
if self.watermark_file:
return Image.open(self.watermark_file)
if self.watermark_path:
return Image.open(self.watermark_path)
示例8: _preinit_pil
def _preinit_pil():
"""Loads the standard PIL file format drivers. Returns True if ``preinit()``
was called (and there's a potential that more drivers were loaded) or False
if there is no possibility that new drivers were loaded.
"""
global _pil_init
if _pil_init < 1:
Image.preinit()
_pil_init = 1
return True
return False
示例9: process_zipfile
def process_zipfile(self):
if os.path.isfile(self.zip_file.path):
# TODO: implement try-except here
zip = zipfile.ZipFile(self.zip_file.path)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
count = 1
if self.gallery:
gallery = self.gallery
else:
gallery = Gallery.objects.create(title=self.title,
title_slug=slugify(self.title),
description=self.description,
is_public=self.is_public)
from cStringIO import StringIO
for filename in zip.namelist():
if filename.startswith('__'): # do not process meta files
continue
data = zip.read(filename)
if len(data):
try:
# the following is taken from django.newforms.fields.ImageField:
# load() is the only method that can spot a truncated JPEG,
# but it cannot be called sanely after verify()
trial_image = Image.open(StringIO(data))
trial_image.load()
# verify() is the only method that can spot a corrupt PNG,
# but it must be called immediately after the constructor
trial_image = Image.open(StringIO(data))
trial_image.verify()
except Exception, e:
# if a "bad" file is found we just skip it.
raise e
continue
while 1:
title = ' '.join([self.title, str(count)])
slug = slugify(title)
try:
p = Photo.objects.get(title_slug=slug)
except Photo.DoesNotExist:
photo = Photo(title=title,
title_slug=slug,
caption=self.caption,
is_public=self.is_public)
photo.image.save(filename, ContentFile(data))
gallery.photos.add(photo)
count = count + 1
break
count = count + 1
zip.close()
return gallery
示例10: generate_lenna
def generate_lenna():
"""
See also:
http://en.wikipedia.org/wiki/Lenna
http://sipi.usc.edu/database/database.php?volume=misc&image=12
"""
tmp = tempfile.TemporaryFile()
lennapath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg')
with open(lennapath, "r+b") as lennafile:
Image.open(lennafile).save(tmp, 'JPEG')
tmp.seek(0)
return tmp
示例11: detect_border_color
def detect_border_color(img):
mask = Image.new("1", img.size, 1)
w, h = img.size[0] - 2, img.size[1] - 2
if w > 0 and h > 0:
draw = ImageDraw.Draw(mask)
draw.rectangle([1, 1, w, h], 0)
return ImageStat.Stat(img.convert("RGBA").histogram(mask)).median
示例12: process
def process(self, img):
# get watermark
wm = self._get_watermark()
wm_size = wm.size
if self.scale:
if isinstance(self.scale, (int, float)) and self.scale != 1:
wm_size[0] *= self.scale
wm_size[1] *= self.scale
wm = wm.scale(wm_size)
elif self.scale == True:
wm = ResizeToFit(width=img.size[0], height=img.size[1],
upscale=True).process(wm)
wm_size = wm.size
# prepare image for overlaying (ensure alpha channel)
if img.mode != 'RGBA':
img = img.convert('RGBA')
# create a layer to place the watermark
layer = Image.new('RGBA', img.size, (0,0,0,0))
coords = _process_coords(img.size, wm_size, self.position)
if self.repeat:
sx = coords[0] % wm_size[0] - wm_size[0]
sy = coords[1] % wm_size[1] - wm_size[1]
for x in range(sx, img.size[0], wm_size[0]):
for y in range(sy, img.size[1], wm_size[1]):
layer.paste(wm, (x,y))
else:
layer.paste(wm, coords)
if self.opacity < 1:
alpha = layer.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity)
layer.putalpha(alpha)
# merge watermark layer
img = Image.composite(layer, img, layer)
return img
示例13: resized
def resized(self, h=0, w=0, footer=True, extended=True, crop=False, upscale=False):
"""Get the image, resized and optionally watermarked"""
fn = self.image.file.name
suffix = ['_']
if not w:
suffix.append('0')
else:
suffix.append(str(w))
suffix.append('x')
if not h:
suffix.append('0')
else:
suffix.append(str(h))
if footer or extended:
suffix.append('-')
if footer:
suffix.append('w')
if extended:
suffix.append('e')
suffix = ''.join(suffix)
fn = get_scaled_media_path(self, filename=fn, suffix=suffix)
if os.path.exists(fn):
img = Image.open(fn)
log.debug('returning cached image: %s', fn)
else:
img = Image.open(self.image.file.name)
cw, ch = img.size
if h == 0 and w == 0:
h = ch
w = cw
if h != ch or w != cw:
img = resize_image(img, h, w, crop=crop, upscale=upscale)
if footer or extended:
img = add_watermark(img, footer=footer, extended=extended)
img.save(fn)
log.debug('Created and cached new image: %s', fn)
return img, fn
示例14: process
def process(cls, img, fmt, obj):
if cls.width and cls.height:
background_color = ImageColor.getrgb(cls.background_color)
#FIXME : Image is not imported but it never raises exception so ...
bg_picture = Image.new("RGB", (cls.width, cls.height), background_color)
## paste it
bg_w, bg_h = bg_picture.size
img_w, img_h = img.size
coord_x, coord_y = (bg_w - img_w) / 2, (bg_h - img_h) / 2
bg_picture.paste(img, (coord_x, coord_y, coord_x + img_w, coord_y + img_h))
return bg_picture, fmt
示例15: __getattribute__
def __getattribute__(self, key):
if key == "username":
if not object.__getattribute__(self, "username") and self.id:
self.username = self.user.username
self.save()
return self.username
if key == "main_profile_pic":
if not object.__getattribute__(self, "main_profile_pic"):
try:
default_photo = Photo.objects.filter(user_default=True)[0]
return default_photo
except IndexError:
user_fallback = "%s/photos/%s" % (settings.MEDIA_ROOT, "img_user_fallback.png")
try:
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
photo = Photo(user_default=True)
photo.save()
Photo.objects.filter(pk=photo.pk).update(image="photos/img_user_fallback.png")
photo = Photo.objects.get(pk=photo.pk)
fp.close()
return photo
except Exception, e:
user_fallback = "%s/images/%s" % (settings.GLOBALS_STATIC_ROOT, "img_user_fallback.png")
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
fp2 = open(user_fallback, "r")
target_file = File(fp2)
name = "img_user_fallback.png"
photo = Photo(user_default=True)
photo.image.save(name, target_file, save=True)
fp.close()
fp2.close()
return photo