本文整理汇总了Python中wand.image.Image.rotate方法的典型用法代码示例。如果您正苦于以下问题:Python Image.rotate方法的具体用法?Python Image.rotate怎么用?Python Image.rotate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wand.image.Image
的用法示例。
在下文中一共展示了Image.rotate方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: autorotate_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def autorotate_image(in_path, out_path):
try:
metadata = pyexiv2.ImageMetadata(in_path)
metadata.read()
orient = int(metadata['Exif.Image.Orientation'].value)
except:
logger.warn(
"Image {0} did not have any EXIF rotation, did not rotate."
.format(in_path))
return
img = Image(filename=in_path)
if orient == 1:
logger.info("Image {0} is already rotated.".format(in_path))
shutil.copyfile(in_path, out_path)
return
elif orient == 2:
img.flip()
elif orient == 3:
img.rotate(180)
elif orient == 4:
img.flop()
elif orient == 5:
img.rotate(90)
img.flip()
elif orient == 6:
img.rotate(90)
elif orient == 7:
img.rotate(270)
img.flip()
elif orient == 8:
img.rotate(270)
img.save(filename=out_path)
示例2: convert_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def convert_image(pngfile, pf, outdir=".",
resize=1000, format="jpeg", rotate=0,
rows=':', cols=':', labelrows=None, labelcols=None):
resizefile = op.join(outdir, pf + ".resize.jpg")
mainfile = op.join(outdir, pf + ".main.jpg")
labelfile = op.join(outdir, pf + ".label.jpg")
img = Image(filename=pngfile)
exif = dict((k, v) for k, v in img.metadata.items() if k.startswith('exif:'))
# Rotation, slicing and cropping of main image
if rotate:
img.rotate(rotate)
if resize:
w, h = img.size
if min(w, h) > resize:
if w < h:
nw, nh = resize, resize * h / w
else:
nw, nh = resize * w / h, resize
img.resize(nw, nh)
logging.debug("Image `{0}` resized from {1}px:{2}px to {3}px:{4}px".\
format(pngfile, w, h, nw, nh))
img.format = format
img.save(filename=resizefile)
rimg = img.clone()
if rows != ':' or cols != ':':
w, h = img.size
ra, rb = slice(rows, h)
ca, cb = slice(cols, w)
# left, top, right, bottom
logging.debug("Crop image to {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
img.crop(ca, ra, cb, rb)
img.format = format
img.save(filename=mainfile)
else:
mainfile = resizefile
# Extract text labels from image
if labelrows or labelcols:
w, h = rimg.size
if labelrows and not labelcols:
labelcols = ':'
if labelcols and not labelrows:
labelrows = ':'
ra, rb = slice(labelrows, h)
ca, cb = slice(labelcols, w)
logging.debug("Extract label from {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
rimg.crop(ca, ra, cb, rb)
rimg.format = format
rimg.save(filename=labelfile)
else:
labelfile = None
return resizefile, mainfile, labelfile, exif
示例3: magick_crop
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def magick_crop(self, image_url=None, dataX=0, dataY=0, dataWidth=0, dataHeight=0, dataRotate=0, dataScaleX=1, dataScaleY=1, **kw):
if 'ir.attachment' in image_url:
# binary -> decode -> wand.image -> imagemagick -> make_blob() -> encode -> binary
img_attachment = request.env['ir.attachment'].browse(int(image_url.split('/')[4].split('_')[0]))
wand_img = Image(blob=getattr(img_attachment, 'datas').decode('base64'))
try:
wand_img.crop(int(dataX), int(dataY), width=int(dataWidth), height=int(dataHeight))
if dataScaleX and dataScaleY:
wand_img.resize(int(wand_img.width * float(dataScaleX)), int(wand_img.height * float(dataScaleY)))
if dataRotate:
wand_img.rotate(int(dataRotate))
img_attachment.write({ 'datas': wand_img.make_blob().encode('base64') })
except Exception as e:
return ': '.join(e)
return 'Magic Crop Completed!'
else:
return 'Please using attachment as image!'
示例4: main
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def main():
# Resize image to height (but do not change the aspect ratio)
#
req_width = 595
req_height = 486
baby_img = Image(filename="baby_cc_sh.png")
baby_img = resize_to_height(baby_img, req_height)
# For this particular image, reflect image along vertical
# axis to have face directed towards right of page.
#
baby_img.flop()
# Create the the gradient transition that will later be used
# in the opacity mask.
#
gradient_blob = create_gradient_blob(req_height, 75, gradient([
(1.0, (0x00, 0x00, 0x00), (0xFF, 0xFF, 0xFF)), # top
]))
gradient_img = Image(blob=gradient_blob)
gradient_img.rotate(90.0)
# When building the opacity mask, must start with an image
# having a solid colour (i.e., begin as a "matte" image).
# Without this, the later "composite_channel" operations
# will simply not work.
#
opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
white_field = new_blank_png(230, req_height, Color('white'))
black_field = new_blank_png(290, req_height, Color('black'))
opacity_mask.composite(white_field, 0, 0)
opacity_mask.composite(black_field, 230+75, 0)
opacity_mask.composite(gradient_img, 230, 0)
# Now take the resized baby image and have it fade to the right
# (in order to blend with later operations).
#
full_img = new_blank_png(req_width, req_height)
full_img.composite(baby_img, 0, 0)
full_img.composite_channel(channel='all_channels', image=opacity_mask, operator='copy_opacity')
示例5: reorient_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def reorient_image(cls, contents):
try:
handler = ImageHandler(blob=contents)
except IOError:
return contents
orientation = handler.metadata.get('exif:Orientation')
if not orientation:
return contents
{
1: lambda: handler,
2: lambda: handler.flop(),
3: lambda: handler.rotate(180),
4: lambda: handler.flip(),
5: lambda: handler.flip().rotate(90),
6: lambda: handler.rotate(90),
7: lambda: handler.flop().rotate(90),
8: lambda: handler.rotate(270),
}[int(orientation)]()
return handler.make_blob()
示例6: autorotate_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def autorotate_image(in_path, out_path):
""" Rotate an image according to its EXIF orientation tag.
:param in_path: Path to image that should be rotated
:type in_path: unicode
:param out_path: Path where rotated image should be written to
:type out_path: unicode
"""
try:
metadata = pyexiv2.ImageMetadata(in_path)
metadata.read()
orient = int(metadata['Exif.Image.Orientation'].value)
except:
logger.warn(
"Image {0} did not have any EXIF rotation, did not rotate."
.format(in_path))
return
img = Image(filename=in_path)
if orient == 1:
logger.info("Image {0} is already rotated.".format(in_path))
shutil.copyfile(in_path, out_path)
return
elif orient == 2:
img.flip()
elif orient == 3:
img.rotate(180)
elif orient == 4:
img.flop()
elif orient == 5:
img.rotate(90)
img.flip()
elif orient == 6:
img.rotate(90)
elif orient == 7:
img.rotate(270)
img.flip()
elif orient == 8:
img.rotate(270)
img.save(filename=out_path)
示例7: process_upload
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [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: Image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
return lines
#For all the png in the folder
for filename in glob.glob("*-t.png"):
im = Image(filename=filename)
#Save the widht and height of the thumbnail
th = im.height
tw = im.width
#Crop the image
l = crop_image(im)
top = l[1]
bottom = l[2]
im.crop(0,l[1],im.width,l[2])
#We rotate so we can use the same code!
im.rotate(90)
print im.height, im.width
l = crop_image(im)
im.crop(0,l[1],im.width,l[2])
left = l[1]
right = l[2]
im.rotate(-90)
#We open the original image so we can crop it too
original = filename.replace('-t','')
oim = Image(filename=original)
ow = oim.width
oh = oim.height
oim.crop((left * ow) /tw,(top * oh) / th,(right * ow) / tw,(bottom * oh) / th)
im.save(filename=filename+'crop.png')
oim.save(filename=original+'crop.png')
示例9: download_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def download_image(request, datafile_id, region, size, rotation,
quality, format=None): #@ReservedAssignment
# Get datafile (and return 404 if absent)
try:
datafile = DataFile.objects.get(pk=datafile_id)
except DataFile.DoesNotExist:
return HttpResponseNotFound()
is_public = datafile.is_public()
if not is_public:
# Check users has access to datafile
if not has_datafile_download_access(request=request,
datafile_id=datafile.id):
return HttpResponseNotFound()
buf = StringIO()
try:
file_obj = datafile.get_image_data()
if file_obj is None:
return HttpResponseNotFound()
from contextlib import closing
with closing(file_obj) as f:
with Image(file=f) as img:
if len(img.sequence) > 1:
img = Image(img.sequence[0])
# Handle region
if region != 'full':
x, y, w, h = map(int, region.split(','))
img.crop(x, y, width=w, height=h)
# Handle size
if size != 'full':
# Check the image isn't empty
if 0 in (img.height, img.width):
return _bad_request('size', 'Cannot resize empty image')
# Attempt resize
if not _do_resize(img, size):
return _bad_request('size',
'Invalid size argument: %s' % size)
# Handle rotation
if rotation:
img.rotate(float(rotation))
# Handle quality (mostly by rejecting it)
if quality not in ['native', 'color']:
return _get_iiif_error('quality',
'This server does not support greyscale or bitonal quality.')
# Handle format
if format:
mimetype = mimetypes.types_map['.%s' % format.lower()]
img.format = format
if mimetype not in ALLOWED_MIMETYPES:
return _invalid_media_response()
else:
mimetype = datafile.get_mimetype()
# If the native format is not allowed, pretend it doesn't exist.
if mimetype not in ALLOWED_MIMETYPES:
return HttpResponseNotFound()
img.save(file=buf)
response = HttpResponse(buf.getvalue(), content_type=mimetype)
response['Content-Disposition'] = \
'inline; filename="%s.%s"' % (datafile.filename, format)
# Set Cache
if is_public:
patch_cache_control(response, public=True, max_age=MAX_AGE)
else:
patch_cache_control(response, private=True, max_age=MAX_AGE)
return response
except WandException:
return HttpResponseNotFound()
except ValueError:
return HttpResponseNotFound()
except IOError:
return HttpResponseNotFound()
示例10: slice02
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def slice02():
# Resize image to height (but do not change the aspect ratio)
#
req_width = 595
req_height = 486
baby_img = Image(filename=IMAGE_PATH + "baby_cc_sh.png")
baby_img = resize_to_height(baby_img, req_height)
# For this particular image, reflect image along vertical
# axis to have face directed towards right of page.
#
baby_img.flop()
# Create the the gradient transition that will later be used
# in the opacity mask.
#
gradient_blob = create_gradient_blob(req_height, 75, gradient([
(1.0, (0x00, 0x00, 0x00), (0xFF, 0xFF, 0xFF)), # top
]))
gradient_img = Image(blob=gradient_blob)
gradient_img.rotate(90.0)
# When building the opacity mask, must start with an image
# having a solid colour (i.e., begin as a "matte" image).
# Without this, the later "composite_channel" operations
# will simply not work.
#
opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
left_field = new_blank_png(230, req_height, Color('white'))
right_field = new_blank_png(290, req_height, Color('black'))
opacity_mask.composite(left_field, 0, 0)
opacity_mask.composite(right_field, 230+75, 0)
opacity_mask.composite(gradient_img, 230, 0)
# Now take the resized baby image and have it fade to the right
# (in order to blend with later operations).
#
face_img = new_blank_png(req_width, req_height)
face_img.composite(baby_img, 0, 0)
face_img.composite_channel(channel='all_channels', image=opacity_mask,
operator='copy_opacity')
# Bring in the illustrative image that will eventually be blended in
# with the child's face.
#
accent_img = Image(filename = IMAGE_PATH + "funky_illustration.png")
accent_img = resize_to_percent(accent_img, 60)
accent_img = resize_to_height(accent_img, 486)
cropped_img = accent_img.clone()
cropped_img.crop(top=0, left=275, width=340, height=486)
screen_img = new_blank_png(340, 486, color=Color('rgb(150,150,150)'))
cropped_img.composite_channel(channel='all_channels', image=screen_img,
operator='screen')
accent_img = new_blank_png(req_width, req_height)
accent_img.composite_channel(channel='all_channels', image=cropped_img,
operator='over', left=255, top=0)
accent_img.gaussian_blur(3.0, 1.0)
opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
left_field = new_blank_png(260, req_height, Color('black'))
right_field = new_blank_png(290, req_height, Color('white'))
opacity_mask.composite(left_field, 0, 0)
opacity_mask.composite(right_field, 260+75, 0)
gradient_img.rotate(180)
opacity_mask.composite(gradient_img, 260, 0)
accent_img.composite_channel(channel='all_channels', image=opacity_mask,
operator='copy_opacity')
# Now layer the accent image with the child's face
#
accent_img.composite_channel(channel='all_channels', image=face_img,
operator='over')
full_slice = accent_img
# Finally, add the text field on the right of the image.
#
text_field = new_blank_png(212, req_height, color=Color('rgb(190,30,45)'))
text_field_mask = new_blank_png(212, req_height, color=Color('rgb(220,220,220)'))
text_field.composite_channel(channel='all_channels', image=text_field_mask,
operator='copy_opacity')
full_slice.composite(text_field, 384, 0)
draw = Drawing()
draw.font = FONT_BOLD
draw.font_size = 24
draw.fill_color = Color('white')
draw.text(395, 175, "Liam Mulcahy")
draw.font = FONT_REGULAR
draw.font_size = 20
draw.text(395, 200, "Eyes to the Future")
draw.font = FONT_ITALIC
draw.font_size = 20
draw.text(395, 250, 'How dreams of')
draw.text(395, 275, 'future enterprise')
draw.text(395, 300, 'success are')
draw.text(395, 325, 'starting while still')
draw.text(395, 350, 'in nappies!')
draw(full_slice)
#.........这里部分代码省略.........
示例11: upload_attachement
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import rotate [as 别名]
def upload_attachement(self, issue=False, **post):
cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
message = {}
user = request.env['res.users'].browse(uid)
voucher_name = None
if not issue and request.httprequest.method == 'POST':
try:
voucher_name = [txt[1] for txt in request.env['project.issue'].fields_get(['voucher_type'])['voucher_type']['selection'] if txt[0] == post.get('voucher_type')][0]
if len(post.get('name'))<1:
post['name'] = '%s %s' % (user.name,time.strftime("%x")) # Why?
project = request.env['project.project'].search(['&',('partner_id','=',user.partner_id.id),('use_voucher','=',True)])
issue = request.env['project.issue'].create({'partner_id': user.partner_id.id,
'name': '%s %s' % (voucher_name,post.get('name','')),
'description': post.get('description'),
'project_id': project[0].id if len(project) > 0 else None,
'voucher_type': post.get('voucher_type'),
})
except Exception as e:
message['danger'] = _('Could not create an issue %s') % e
if issue and request.httprequest.method == 'POST':
issue.write({'partner_id': user.partner_id.id, 'name': '%s %s' % (voucher_name,post.get('name','')), 'description': post.get('description')})
if issue and request.httprequest.method == 'POST' and post.get('ufile'):
_logger.debug("This is attachement post %s /issue/nn" % (post))
blob = post['ufile'].read()
attachment = request.env['ir.attachment'].create({
'name': post['ufile'].filename,
'res_name': issue.name,
'res_model': 'project.issue',
'res_id': issue.id,
'datas': base64.encodestring(blob),
'datas_fname': post['ufile'].filename,
})
if attachment.mimetype == 'application/pdf':
attachment.pdf2image(800,1200)
elif attachment.mimetype in ['image/jpeg','image/png','image/gif']:
orientation = {
'top_left': 0,
'left_top': 0,
'right_top': 90,
'top_right': 90,
'right_bottom': 180,
'bottom_right': 180,
'left_bottom': 270,
'bottom_left': 270,
}
try:
img = Image(blob=blob)
img.rotate(orientation.get(img.orientation))
attachment.datas = base64.encodestring(img.make_blob(format='jpg'))
except:
pass
message['success'] = _('Voucher uploaded %s (%s)') % (issue.name,issue.id)
_logger.error("This is a %s and %s and %s, %s" % (type(issue),isinstance(issue,models.Model),issue,request.httprequest.url))
return request.website.render("website_project_issue.upload_attachement", {
'issue': False if re.search("upload_voucher",request.httprequest.url) is not None else issue,
'message': message,
'attachements': issue and request.env['ir.attachment'].search([('res_model','=','project.issue'),('res_id','=',issue.id)]) or False,
})