Python PIL.Image 模块,ROTATE_270 实例源码
我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用PIL.Image.ROTATE_270。
def font_variant(self, font=None, size=None, index=None, encoding=None):
"""
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this
object.
:return: A FreeTypeFont object.
"""
return FreeTypeFont(font=self.path if font is None else font,
size=self.size if size is None else size,
index=self.index if index is None else index,
encoding=self.encoding if encoding is None else
encoding)
##
# Wrapper that creates a transposed font from any existing font
# object.
#
# @param font A font object.
# @param orientation An optional orientation. If given,this should
# be one of Image.FLIP_LEFT_RIGHT,Image.FLIP_TOP_BottOM,
# Image.ROTATE_90,Image.ROTATE_180,or Image.ROTATE_270.
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer,1 through 8
exif_transpose_sequences = [ # corresponding to the following
[],
[Image.FLIP_LEFT_RIGHT],
[Image.ROTATE_180],
[Image.FLIP_TOP_BottOM],
[Image.FLIP_LEFT_RIGHT, Image.ROTATE_90],
[Image.ROTATE_270],
[Image.FLIP_TOP_BottOM,
[Image.ROTATE_90],
]
try:
if im._getexif() is not None:
seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1]
return functools.reduce(lambda im, op: im.transpose(op), seq, im)
else:
return im
except KeyError:
return im
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer, im)
else:
return im
except KeyError:
return im
def handle_exif(image_file):
with Image.open(image_file) as image:
orientation_key = 274
exif = image._getexif()
format = image.format
if exif and orientation_key in exif:
orientation = exif[orientation_key]
rotate_values = {
3: Image.ROTATE_180,
6: Image.ROTATE_270,
8: Image.ROTATE_90
}
if orientation in rotate_values:
image = image.transpose(rotate_values[orientation])
image_io = BytesIO()
image.save(image_io, format)
return image_io
def getsize(self, text):
w, h = self.font.getsize(text)
if self.orientation in (Image.ROTATE_90, Image.ROTATE_270):
return h, w
return w, h
def __init__(self, font, orientation=None):
"""
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given,this should
be one of Image.FLIP_LEFT_RIGHT,
Image.ROTATE_90,or Image.ROTATE_270.
"""
self.font = font
self.orientation = orientation # any 'transpose' argument,or None
def dump_image(self, bg_color=0xffffffff):
from PIL import Image
packed_image = Image.new('RGBA', self.size, bg_color)
for image_rect in self.image_rect_list:
image = image_rect.image.crop()
if image_rect.rotated:
image = image.transpose(Image.ROTATE_270)
packed_image.paste(image, (image_rect.left, image_rect.top, image_rect.right, image_rect.bottom))
return packed_image
def transpose(self, opts): ###############################################
self.logger.debug("Transposing image %s: %s"
% (self.file_path, str(opts)))
# Parse possible arguments
num_args = 0
if "flipvert" in opts:
method = Image.FLIP_LEFT_RIGHT
num_args += 1
if "fliphorz" in opts:
method = Image.FLIP_TOP_BottOM
num_args += 1
if "rotate90" in opts:
method = Image.ROTATE_90
num_args += 1
if "rotate180" in opts:
method = Image.ROTATE_180
num_args += 1
if "rotate270" in opts:
method = Image.ROTATE_270
num_args += 1
if num_args != 1:
raise DirpyUserError(
"Transpose requires exactly one option: %s" % str(opts))
# Now rotate
try:
self.im_in = self.im_in.transpose(method)
self.out_x, self.out_y = self.im_in.size
self.modified = True
except Exception as e:
raise DirpyFatalError(
"Error transposing image %s: %s" % (self.file_path,e))
# Write an image to a BytesIO output buffer
def __generateRotatedImage(self, image):
"""Use the current rotation of this `ImageFile` to rotate :class:`PIL.Image`.
:param image: The input image.
:return image: The output image."""
if self.rotation == 1:
image = image.transpose(Image.ROTATE_90)
elif self.rotation == 2:
image = image.transpose(Image.ROTATE_180)
elif self.rotation == 3:
image = image.transpose(Image.ROTATE_270)
return image
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer,1 through 8
exif_transpose_sequences = [ # corresponding to the following
[],
]
try:
seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1]
except Exception:
return im
else:
return functools.reduce(lambda im, im)
# def average_color_pixels(image,pixels):
# r,g,b = 0,0
# for pixel in pixels:
# x,y = pixel
# cr,cg,cb = image.getpixel((x,y))
# r+=cr
# g+=cg
# b+=cb
# total = len(pixels)
# return (r/total,g/total,b/total)
def getBuffer(self):
"""Gets the copy of a buffer"""
return self.buffer.transpose(Image.ROTATE_270)
def exif_orientation(im):
try:
exif = im._getexif()
except Exception:
# There are many ways that _getexif fails,we're just going to blanket
# cover them all.
return im
if exif is None:
return im
orientation = exif.get(0x0112)
if orientation == 2:
im = im.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3:
im = im.transpose(Image.ROTATE_180)
elif orientation == 4:
im = im.transpose(Image.FLIP_TOP_BottOM)
elif orientation == 5:
im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 6:
im = im.transpose(Image.ROTATE_270)
elif orientation == 7:
im = im.transpose(Image.ROTATE_90).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 8:
im = im.transpose(Image.ROTATE_90)
return im
# Low-tech approach to work around the too strict URLValidator.
# Context: https://code.djangoproject.com/ticket/20264
# replace() isn't super elegant,but I prefer this to having to copy/paste the whole big regexp
# soup from URLValidator so that I can add one underscore...
def process_image(data, mime_type):
stream = io.BytesIO(data)
try:
img = Image.open(stream)
except OSError:
raise ValueError('Invalid image data')
if mime_type == 'image/jpeg' and img.format == 'JPEG':
format = "JPEG"
subsampling = 'keep'
# check exif information for orientation
if hasattr(img, '_getexif'):
x = img._getexif()
if x and EXIF_ORIENTATION in x and x[EXIF_ORIENTATION] > 1 and x[EXIF_ORIENTATION] < 9:
orientation = x[EXIF_ORIENTATION]
subsampling = get_sampling(img)
if orientation == 2:
# Vertical Mirror
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3:
# Rotation 180°
img = img.transpose(Image.ROTATE_180)
elif orientation == 4:
# Horizontal Im
img = img.transpose(Image.FLIP_TOP_BottOM)
elif orientation == 5:
# Horizontal Im + Rotation 90° ccw
img = img.transpose(Image.FLIP_TOP_BottOM).transpose(Image.ROTATE_90)
elif orientation == 6:
# Rotation 270°
img = img.transpose(Image.ROTATE_270)
elif orientation == 7:
# Horizontal Im + Rotation 270°
img = img.transpose(Image.FLIP_TOP_BottOM).transpose(Image.ROTATE_270)
elif orientation == 8:
# Rotation 90°
img = img.transpose(Image.ROTATE_90)
save_kwargs = {'subsampling': subsampling, 'quality': 85}
elif mime_type == 'image/png' and img.format == 'PNG':
format = "PNG"
save_kwargs = {'icc_profile': img.info.get("icc_profile")}
else:
raise ValueError('Unsupported image format')
if img.size[0] > 512 or img.size[1] > 512:
img.thumbnail((512, 512))
stream = io.BytesIO()
img.save(stream, format=format, optimize=True, **save_kwargs)
data = stream.getbuffer().tobytes()
hasher = hashlib.md5()
hasher.update(data)
cache_hash = hasher.hexdigest()
return data, cache_hash, format
def process_image(data, mime_type):
stream = io.BytesIO(data)
try:
img = Image.open(stream)
except OSError:
raise JSONHTTPError(400, body={'errors': [{'id': 'bad_arguments', 'message': 'Invalid image data'}]})
if mime_type == 'image/jpeg' and img.format == 'JPEG':
format = "JPEG"
subsampling = 'keep'
# check exif information for orientation
if hasattr(img, 'quality': 85}
elif mime_type == 'image/png' and img.format == 'PNG':
format = "PNG"
save_kwargs = {'icc_profile': img.info.get("icc_profile")}
else:
raise JSONHTTPError(400, 'message': 'Unsupported image format'}]})
if img.size[0] > 512 or img.size[1] > 512:
img.thumbnail((512, format
def rotate_image(input_file, input_Box):
prefix = os.path.splitext(input_file)[0]
x1 = input_Box[0]["x1"]
y1 = input_Box[0]["y1"]
x2 = input_Box[0]["x2"]
y2 = input_Box[0]["y2"]
im = Image.open(input_file)
im1 = im.transpose(Image.ROTATE_90)
im2 = im.transpose(Image.ROTATE_180)
im3 = im.transpose(Image.ROTATE_270)
output_file = [
prefix + "_rotate_1.bmp",
prefix + "_rotate_2.bmp",
prefix + "_rotate_3.bmp",
]
output_Box = [
{
"x1": y1,
"x2": y2,
"y1": SIZE - 1 - x1,
"y2": SIZE - 1 - x2,
},
{
"x1": SIZE - 1 - x1,
"x2": SIZE - 1 - x2,
"y1": SIZE - 1 - y1,
"y2": SIZE - 1 - y2,
{
"x1": SIZE - 1 - y1,
"x2": SIZE - 1 - y2,
"y1": x1,
"y2": x2,
]
im1.save(output_file[0])
im2.save(output_file[1])
im3.save(output_file[2])
# draw_Box(im1,output_Box[0]).save(output_file[0])
# draw_Box(im2,output_Box[1]).save(output_file[1])
# draw_Box(im3,output_Box[2]).save(output_file[2])
return output_file, output_Box
def adjust_image(self, image, adjust):
"""Adjust an image and return None or an Image instance."""
adjusted = False
img = Image.open(image)
if adjust == Container.RESIZE:
# RESIZE adjust the longest size of the image to size of a
# page. The net result is:
#
# new_width <= WIDTH
# new_height <= HEIGHT
#
width, height = img.size
ratio = min((WIDTH/float(width), HEIGHT/float(height)))
width, height = int(ratio*width+0.5), int(ratio*height+0.5)
resample = Image.BICUBIC if ratio > 1 else Image.ANTIALIAS
img = img.resize((width, height), resample)
adjusted = True
elif adjust == Container.RESIZE_CROP:
# RESIZE_CROP resize first the image as RESIZE,and create
# a new white image of page size,and paste the image in
# the new one. Used to adjust the cover image without
# losing the aspect ratio.
size = img.size
mode = img.mode
# Resize the current image
width, height = size
ratio = min((WIDTH/float(width), int(ratio*height+0.5)
resample = Image.BICUBIC if ratio > 1 else Image.ANTIALIAS
resized_img = img.resize((width, resample)
# Create a new white image and paste the resized image
x, y = (WIDTH - width) / 2, (HEIGHT - height) / 2
img = Image.new(mode, (WIDTH, HEIGHT), '#ffffff')
img.paste(resized_img, (x, y))
adjusted = True
elif adjust == Container.ROTATE:
# ROTATE check first if the image is widther than heigher,
# and rotate the image in this case. Used for double page
# images.
width, height = img.size
if float(width) / float(height) > 1.0:
img = img.transpose(Image.ROTATE_270)
adjusted = True
# elif adjust == Container.SPLIT:
# pass
elif adjust:
raise ValueError('Value for adjust not found')
return img, adjusted
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。