本文整理汇总了Python中wand.image.Image.transform方法的典型用法代码示例。如果您正苦于以下问题:Python Image.transform方法的具体用法?Python Image.transform怎么用?Python Image.transform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wand.image.Image
的用法示例。
在下文中一共展示了Image.transform方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resize_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def resize_image(self, img_path, size_config, size_name, dest_path, compress=False):
#open image
img = Image(filename=img_path)
#transform using resize config
img.transform(resize=size_config)
'''
exProcessor = ExifData()
#rotate image if necessary
if exProcessor.check_orientation(img) in [6, 7]:
img.rotate(90)
img.metadata['exif:Orientation'] = 1
if exProcessor.check_orientation(img) in [6, 8]:
img.rotate(-90)
img.metadata['exif:Orientation'] = 1
if exProcessor.check_orientation(img) in [3, 4]:
img.rotate(180)
img.metadata['exif:Orientation'] = 1
'''
# Detect file extention
fileName, fileExtension = os.path.splitext(img_path)
#save img
fileName = ''.join([fileName, '_', size_name, fileExtension])
fileName = os.path.basename(fileName)
fileName = os.path.abspath(os.path.join(dest_path, fileName))
# Compress option?
if compress:
img.compression_quality = 70
img.save(filename=fileName)
return fileName
示例2: _create_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def _create_image(self, image_argument):
image = None
if isinstance(image_argument, Image):
image = image_argument
if isinstance(image_argument, (str, unicode)):
image_file = urllib.urlopen(image_argument)
image = Image(blob=image_file.read())
elif isinstance(image_argument, dict):
config = image_argument
if 'raw_image' not in config:
raise KeyError("Should have image in config")
if not isinstance(config['raw_image'], Image):
raise TypeError("config['raw_image'] should be Image")
image = config['raw_image']
transforms = config.get('transforms', [])
for t in transforms:
image.transform(**t)
if image is None:
raise ValueError("Generate Fail")
return image
示例3: generate_square_img
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def generate_square_img(self, img_path, size_config, size_img, size_name, dest_path):
#open_image
img = Image(filename=img_path)
#transform with resize scale config
img.transform(resize=size_config)
#try to crop, calculate width crop first
target_size = size_img[1] #use one because its square
width, height = img.size
#print "width, height ", width, height
crop_start, crop_end = [0, 0] #add new size params
#calculate
crop_start = (width - target_size) / 2
crop_end = crop_start + target_size
#print crop_start, crop_end, target_size, (crop_end - crop_start)
'''
exProcessor = ExifData()
#rotate image if necessary
if exProcessor.check_orientation(img) in [6, 7]:
img.rotate(90)
img.metadata['exif:Orientation'] = 1
if exProcessor.check_orientation(img) in [6, 8]:
img.rotate(-90)
img.metadata['exif:Orientation'] = 1
if exProcessor.check_orientation(img) in [3, 4]:
img.rotate(180)
img.metadata['exif:Orientation'] = 1
'''
#do cropping
with img[crop_start:crop_end, :] as square_image:
#save
square_image.save(filename=''.join([dest_path, size_name, '.jpg']))
示例4: PDFHandler
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
class PDFHandler(BaseHandler):
def __init__(self, filename, file_type='pdf'):
self.local_file = filename
try:
self.im = WandImage(filename=filename + '[0]')
except Exception as e:
self.im = None
print e
self.file_type = file_type
self.format = file_type
self.size = (201, 201)
def get_metadata(self):
with exiftool.ExifTool() as et:
metadata = et.get_metadata(self.local_file)
return metadata
def thumbnail(self, thumb_filename):
if self.im:
self.im.alpha_channel = False
self.im.transform(resize=thumbnail_size)
self.im.save(filename=thumb_filename)
def preview(self, preview_filename):
if self.im:
self.im.save(filename=preview_filename)
示例5: ImageHandler
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
class ImageHandler(BaseHandler):
pil_formats = ['jpg', 'jpeg', 'png', 'eps']
magick_formats = ['psd', 'ai']
def __init__(self, filename, file_type):
self.local_file = filename
self.file_type = file_type
try:
if file_type not in self.magick_formats:
self.im = PILImage.open(filename)
if self.im.mode == 'P':
self.im = self.im.convert('RGBA')
self.size = self.im.size
self.format = self.im.format
self.width = self.im.width
self.height = self.im.height
else:
self.im = WandImage(filename=filename+'[0]')
self.format = file_type
self.size = self.im.size
self.width = self.im.width
self.height = self.im.height
except Exception as e:
print e
def is_smaller(self):
if self.file_type in self.magick_formats:
return False
size = self.size
width = size[0]
height = size[1]
return (width < 200) and (height < 200)
def get_metadata(self):
with exiftool.ExifTool() as et:
metadata = et.get_metadata(self.local_file)
return metadata
def thumbnail(self, thumb_filename):
if self.file_type in self.magick_formats:
self.im.transform(resize=thumbnail_size)
self.im.save(filename=thumb_filename)
else:
self.im.thumbnail((200, 200), PILImage.ANTIALIAS)
self.im.save(thumb_filename, 'JPEG')
def close(self):
if self.file_type not in self.magick_formats:
self.im.close()
示例6: normalize_images
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def normalize_images(follower_ids, dest_dir):
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
for profile_id in follower_ids:
for extn in ['jpg', 'png', 'jpeg']:
src_file = 'images/'+str(profile_id)+'.'+extn
dst_file = dest_dir.rstrip('/')+'/'+str(profile_id)+'.jpg'
if os.path.exists(src_file) and not os.path.exists(dst_file):
with open(src_file, 'rb') as r:
image = Image(blob=r.read())
image.format = 'jpg'
dim = min(image.width, image.height)
dimstr = str(dim)+'x'+str(dim)
image.transform(dimstr,'48x48')
with open(dst_file,'wb') as o:
image.save(o)
示例7: process_upload
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def process_upload(upload, collection='uploads', image_size=(1280, 720),
thumbnail=True):
"""Processes the uploaded images in the posts and also the users avatars.
This should be extensible in future to support the uploading of videos,
audio, etc...
:param _id: The ID for the post, user or anything you want as the filename
:type _id: str
:param upload: The uploaded Werkzeug FileStorage object
:type upload: ``Werkzeug.datastructures.FileStorage``
:param collection: The GridFS collection to upload the file too.
:type collection: str
:param image_size: The max height and width for the upload
:type image_size: Tuple length 2 of int
:param thumbnail: Is the image to have it's aspect ration kept?
:type thumbnail: bool
"""
try:
# StringIO to take the uploaded image to transport to GridFS
output = io.BytesIO()
# All images are passed through Wand and turned in to PNG files.
# Unless the image is a GIF and its format is kept
# Will change if they need thumbnailing or resizing.
img = Image(file=upload)
# If the input file if a GIF then we need to know
gif = True if img.format == 'GIF' else False
animated_gif = True if gif and len(img.sequence) > 1 else False
# Check the exif data.
# If there is an orientation then transform the image so that
# it is always looking up.
try:
exif_data = {
k[5:]: v
for k, v in img.metadata.items()
if k.startswith('exif:')
}
orientation = exif_data.get('Orientation')
orientation = int(orientation)
if orientation: # pragma: no branch
if orientation == 2:
img.flop()
elif orientation == 3:
img.rotate(180)
elif orientation == 4:
img.flip()
elif orientation == 5:
img.flip()
img.rotate(90)
elif orientation == 6:
img.rotate(90)
elif orientation == 7:
img.flip()
img.rotate(270)
elif orientation == 8:
img.rotate(270)
except (AttributeError, TypeError, AttributeError):
pass
if thumbnail:
# If the GIF was known to be animated then save the animated
# then cycle through the frames, transforming them and save the
# output
if animated_gif:
animated_image = Image()
for frame in img.sequence:
frame.transform(resize='{0}x{1}>'.format(*image_size))
# Directly append the frame to the output image
animated_image.sequence.append(frame)
animated_output = io.BytesIO()
animated_output.format = 'GIF'
animated_image.save(file=animated_output)
animated_output.seek(0)
img.transform(resize='{0}x{1}>'.format(*image_size))
else:
# Just sample the image to the correct size
img.sample(*image_size)
# Turn off animated GIF
animated_gif = False
img.format = 'PNG'
uuid = get_uuid()
filename = '{0}.{1}'.format(uuid, 'png')
# Return the file pointer to the start
img.save(file=output)
output.seek(0)
# Place file inside GridFS
m.save_file(filename, output, base=collection)
animated_filename = ''
#.........这里部分代码省略.........
示例8: splitter
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def splitter(originalFile, no_levels=3, zip=False, inichunk=False,
demo=False):
if demo:
print('\nMAPPS Map Spliter **DEMO**, v0.1, 2014.')
else:
print('\nMAPPS Map Spliter, v0.1, 2014.')
sys.stdout.write("\n Importing original image...")
sys.stdout.flush()
img = Image(filename=originalFile)
sys.stdout.write(" complete.\n")
sys.stdout.flush()
imgwidth = img.width
imgheight = img.height
if imgwidth / imgheight != 2:
print('\n Ooops!!! The Image Width to Height ratio should be 2!!!')
return
else:
stem = originalFile.split('.')[0]
if not os.path.exists(stem):
os.makedirs(stem)
else:
print('\n Uh-oh! The directory {} already exists.'.format(stem))
if utils.yesno(' Do you want to replace it?'):
shutil.rmtree(stem)
os.makedirs(stem)
else:
return
levels = range(1, no_levels + 1)
for level in levels:
print('\n Processing Level {}'.format(level))
split = 2 ** level
segs = range(split)
div = 1. / split
for h in segs:
for w in segs:
w1 = int(imgwidth * div * w)
w2 = int(imgwidth * div * (w + 1))
h1 = int(imgheight * div * h)
h2 = int(imgheight * div * (h + 1))
imgtmp = img[w1:w2, h1:h2]
# print(w1, w2, h1, h2)
imgtmp.transform(resize='1440x720!')
imgtmp.format = 'jpeg'
hlevel = '{0:03d}'.format(h + 1)
wlevel = '{0:03d}'.format(w + 1)
saveas = os.path.join(stem, '{}_{}_{}_{}.jpg'.format(
stem, level, hlevel, wlevel))
print(' Writing: {}'.format(saveas))
imgtmp.save(filename=saveas)
if imgtmp.width != 1440:
print('ERROR: image width = {}\n'.format(imgtmp.width))
if imgtmp.height != 720:
print('ERROR: image height = {}\n'.format(imgtmp.height))
# process input image
img.transform(resize='1440x720')
img.format = 'jpeg'
img.save(filename=os.path.join(stem, '{}_0_001_001.jpg'.format(
stem)))
# create ini file segment
if inichunk:
utils.inifix(stem, no_levels)
# zip output
if zip:
print('\n Zipping output to {}.zip'.format(stem))
zipf = zipfile.ZipFile('{}.zip'.format(stem), 'w')
utils.zipdir('{}/'.format(stem), zipf)
zipf.close()
shutil.rmtree(stem)
print('\nFinished!\n')
return
示例9: __init__
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
class Panel:
def __init__(self, background=None, chars=None, scene=None, doublewide=False):
if background is None:
background = randomize_background()
self.background = Image(filename=background)
self.doublewide = doublewide
if self.doublewide is True:
self.background.crop(0, 0, self.background.height, self.background.height)
self.background.transform(resize='1000x500^')
self.background.transform('1000x500')
else:
self.background.crop(0, 0, self.background.height, self.background.height)
self.background.transform(resize='500')
self.background.transform(resize='500x500')
self.chars = chars
self.scene = scene
draw.font = 'plugins/py_toon/fonts/DejaVuSansMono.ttf'
draw.font_size = 15
draw.text_kerning = 1
draw.text_alignment = 'left'
def setup(self):
self.add_characters()
self.speech_bubbles()
self.background = self.render()
return self.background
def speech_bubbles(self):
curx = 15
cury = 15
for action in self.scene[1]:
actor = action[0]
line = action[1]
if not line:
continue
line = textwrap.fill(line, 20)
metrics = draw.get_font_metrics(self.background, line, True)
ctext = int(metrics.text_width / 2.0)
draw.fill_color = Color('white')
draw.stroke_color = Color('black')
draw.stroke_width = 1.0
char_center = actor.img.x + int(actor.img.width / 2.0)
text_center = int(metrics.text_width / 2.0)
if len(self.scene[1]) == 1:
cury = randrange(50, 125 + 20)
else:
max_y = cury + 20
if max_y < 1: max_y = 245
cury = randrange(cury, max_y)
curx = char_center - text_center
if curx < 25: curx = 25
if curx > self.background.width - int(metrics.text_width):
curx = self.background.width - int(metrics.text_width) - 15
curx = int(curx)
cury = int(cury)
if line.strip() != '':
draw.round_rectangle(curx - 10, cury, curx + metrics.text_width + 10, cury + metrics.text_height + 5, 5, 5)
draw.fill_color = Color('black')
draw.text(curx, cury + 15, line)
curx += metrics.text_width + 10
cury += int(metrics.text_height + 10)
def add_characters(self):
parts = self.background.width / len(self.chars.keys())
curx = 0
cury = 0
char_count = 0
for i in self.chars.items():
char = i[1]
if self.doublewide is True:
#char.img.resize(175, 175)
char.img.transform(resize='x150')
else:
char.img.resize(125, 125)
### contain the character in this "box"
char_pos = curx + parts - char.img.width
print 'char_pos:', char_pos
if char_pos < 1:
return 'Not enough space to fit everybody.'
curx = randrange(curx, char_pos)
cury = self.background.height - char.img.height
char.img.x = curx
#.........这里部分代码省略.........
示例10: Card
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
class Card(object):
"""Individual object containing an image and actions to manipulate it.
Posible kwargs to __init__ are filename, file, image, blob. it will load the image from there"""
def __init__(self, *args, **kwargs):
"""Init a new cards with *img* being a wand.image.Image object"""
self.img = Image(*args, **kwargs)
self.border = None
self.changed = True
self.pixmap()
def __del__(self):
self.img.destroy()
def format(self, fmt=None):
if fmt is None:
return self.img.format.lower()
else:
self.img.format = fmt
@set_changed
def resize(self, width, height, newres=300):
"""Resize this card to (*width*, *height*) inches, with a resolution of *newres*"""
self.img.transform(resize=str(int(width*newres)) + "x" + str(int(height*newres)) + "!")
self.img.reset_coords()
self.img.resolution = (newres, newres)
return newres
def width(self):
return self.img.size[0]
def height(self):
return self.img.size[1]
def reset_coords(self):
self.img.reset_coords()
@set_changed
def set_border(self, border):
"""Set a new *border* for this card"""
if self.border is not None:
self.del_border()
self.border = border
with Color(self.border.colour) as colour:
self.img.border(colour, self.border.wide, self.border.wide)
@set_changed
def crop(self, *args, **kwargs):
"""Crop this card *top*, *bottom*, *left* and *right* pixels"""
w, h = self.img.size
if "right" in kwargs:
kwargs["right"] = w - kwargs["right"]
if "bottom" in kwargs:
kwargs["bottom"] = h - kwargs["bottom"]
self.img.crop(*args, **kwargs)
self.reset_coords()
def del_border(self):
"""Remove the border of this card"""
if self.border is not None:
w = self.border.wide
self.crop(top=w, bottom=w, right=w, left=w)
self.border = None
self.changed = True
@set_changed
def trim(self, fuzz=13):
self.img.trim(fuzz=fuzz)
self.reset_coords()
def save_as(self, filename):
"""Save this card in a file named *filename*"""
self.img.save(filename = filename)
def split(self, rows, cols, separation=0):
"""Divide this cards in *rows* by *cols* cards, and returns a list"""
width, hight = self.img.size
width, hight = (int(width), int(hight))
cardWidth = (width - separation * (cols-1)) / cols
cardHight = (hight - separation * (rows-1)) / rows
res = []
for i in range(rows):
for j in range(cols):
with self.img.clone() as clon:
clon.crop(top=i*cardHight+i*separation, width=cardWidth, left=j*cardWidth+j*separation, height=cardHight)
clon.reset_coords()
res.append(Card(image=clon))
return res
@set_changed
def round_corners(self):
"""Round the corners of the card (setting them to alpha)"""
pass
def clone(self):
c = Card(image=self.img.clone())
c.border = self.border
return c
def pixmap(self):
"""Update and returns the pixmap (QPixmap) of the contained image"""
#.........这里部分代码省略.........
示例11: generate_thumbnail
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import transform [as 别名]
def generate_thumbnail(img_bytes):
img = Image(blob=img_bytes)
# resize to within the box, preserving aspect ratio
img.transform(resize="250x250")
return img.make_blob()