本文整理汇总了Python中wand.image.Image.save方法的典型用法代码示例。如果您正苦于以下问题:Python Image.save方法的具体用法?Python Image.save怎么用?Python Image.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wand.image.Image
的用法示例。
在下文中一共展示了Image.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scale
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def scale(imagePath, face):
# cloneImg.save(filename='{0}-{1}.jpg'.format(imagePath, i))
face_x, face_y, face_w, face_h = face
with Image(filename=imagePath) as img:
img_w = img.size[0]
img_h = img.size[1]
w_delta = ((img_w - face_w) / 2) / NUM_IMAGES
h_delta = ((img_h - face_h) / 2) / NUM_IMAGES
gifImg = Image()
for i in range(NUM_IMAGES, -1, -1):
with img.clone() as cloneImg:
if i == 0:
cloneImg.crop(face_x, face_y, width=face_w, height=face_h)
cloneImg.transform(resize='%dx%d' % (img_w, img_h))
else:
left = max(0, face_x - i * w_delta)
top = max(0, face_y - i * h_delta)
right = min(img_w, face_x + face_w + i * w_delta)
bottom = min(img_h, face_y + face_h + i * h_delta)
cloneImg.crop(left, top, right, bottom)
cloneImg.transform(resize='%dx%d' % (img_w, img_h))
gifImg.sequence.append(cloneImg)
for frame in gifImg.sequence:
with frame:
frame.delay = 20
gifImg.save(filename='%s.gif' % imagePath)
gifImg.close()
return '%s.gif' % imagePath
示例2: main
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def main(argv):
input_file_spec = ''
output_file_path = ''
if len(argv) != 3:
print 'usage: proeprocess_images.py <input_file_spec> <output_path>'
sys.exit(-1)
input_file_spec = argv[1]
output_file_path = argv[2]
file_number = 1
file_path = input_file_spec % file_number
while os.path.exists(file_path):
output_root_file = os.path.splitext(os.path.basename(file_path))[0]
output_path = os.path.join(output_file_path, output_root_file + '.tiff')
print 'processing %s to %s' % (file_path, output_path)
img = Image(filename=file_path)
# remove any letterboxing from top and bottom, unfortunately this eats other
# elements too which can end up interfering negatively with cropping
# trimmer = img.clone()
# trimmer.trim()
# if trimmer.size[0] > 1:
# img = trimmer
# img.reset_coords()
# resize to 180px tall at original aspect ratio
original_size = img.size
scale = 192.0 / float(original_size[1])
scale_width = int(scale * float(original_size[0]))
# always make even width for centering, etc.
# if scale_width % 2 == 1:
# scale_width -= 1
img.resize(width=scale_width, height=192)
img.save(filename=output_path)
file_number += 1
file_path = input_file_spec % file_number
示例3: resize_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [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
示例4: _create_or_update_pdf_thumbnail
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def _create_or_update_pdf_thumbnail(context,pkg_dict_or_resource):
pdf_url=pkg_dict_or_resource['url']
filename, file_extension = os.path.splitext(pdf_url)
if ".pdf" != file_extension.lower() or pkg_dict_or_resource['name'] == "PDF Thumbnail":
return
enabled_pdf_preview = h.asbool(config.get("ckan.odm_nav_concept.generate_pdf_preview", False))
if enabled_pdf_preview:
try:
pdf=Image(filename=pdf_url+"[0]")
pdf.format='png'
pdf.resize(135,201)
temp_dir = os.path.abspath(tempfile.mkdtemp())
temp_img=temp_dir+'/'+pkg_dict_or_resource['id']+'.png'
pdf.save(filename=temp_img)
params = {'package_id':pkg_dict_or_resource['package_id'],'upload':temp_img, 'url':'N/A','format':'PNG','mimetype_inner':'image/png','name':'PDF Thumbnail'}
ckan_url = config.get("ckan.site_url", "")
userobj = context['auth_user_obj']
ckan_auth = userobj.apikey
if context['resource'].name == "PDF Thumbnail":
resource_id=context['resource'].id
params['id']=resource_id
requests.post(ckan_url + 'api/3/action/resource_update',verify=False,data=params,headers={"X-CKAN-API-Key": ckan_auth},files=[('upload', file(params["upload"]))])
else:
requests.post(ckan_url + 'api/3/action/resource_create',verify=False,data=params,headers={"X-CKAN-API-Key": ckan_auth},files=[('upload', file(params["upload"]))])
if os.path.exists(temp_img):
os.remove(temp_img)
except Exception, e:
log.error("Could not generate PDF thumbnail", e)
示例5: PDFHandler
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [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)
示例6: generate_sprite
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def generate_sprite(image_dir, images):
""" (str, list of Image) -> str
Generate sprites with 4 images
Returns the name of the generated sprite
"""
image_width = 160
image_height = 232
sprite = None
left_position = 0
for image in images:
i = get_resized_image(image=image, width=image_width, height=image_height)
if sprite is None:
if i.height == i.width:
sprite = Image(width=image_width*4, height=image_width, background=Color("#fff"))
else:
sprite = Image(width=image_width*4, height=image_height, background=Color("#fff"))
sprite.composite(image=i, left=left_position, top=0)
left_position += image_width
i.destroy()
sprite_file = "%s/sprite.jpg" % (image_dir)
if not isdir(image_dir):
makedirs(image_dir)
sprite.save(filename=sprite_file)
sprite.destroy()
return sprite_file
示例7: appicon
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def appicon(source_image, dest_dir, size_dict):
if not os.path.isdir(dest_dir):
print('the directory does not exist')
return
name = size_dict.get('name')
size_dict = size_dict.get('sizes')
dt = datetime.datetime.today()
dtstring = dt.strftime("%Y-%m-%d %H-%M-%S")
dest_dir = os.path.join(dest_dir, '{}_{}'.format(name, dtstring))
os.makedirs(dest_dir)
img_name, file_ext = os.path.splitext(source_image)
if file_ext not in ('.jpg', '.jpeg', '.png'):
return
for name, size in size_dict.iteritems():
img = Image(filename=source_image)
img.resize(size, size)
img.format = 'png'
img.save(filename=os.path.join(dest_dir, '{}.png'.format(name)))
示例8: pdf2img
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def pdf2img(pdf_path):
print "Converting pdf section to image..."
img = Image(filename=pdf_path)
imgname=pdf_path[:pdf_path.rindex('.')]+ext
print "Saving image: "+imgname[imgname.rindex('\\')+1:]
img.save(filename=imgname)
return imgname
示例9: autorotate_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [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)
示例10: pdf2img
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def pdf2img(pdf_path):
#print "entered pdf2img"
#print "CONVERTING SCALED PDF TO AN IMAGE"
#print "---------------------------------------------------"
img = Image(filename=pdf_path)
imgname=pdf_path[:pdf_path.rindex('.')]+ext
#print "SAVING CONVERTED IMAGE AS: "+imgname[imgname.rindex('/')+1:]
#print "---------------------------------------------------"
img.save(filename=imgname)
return imgname
示例11: series_to_animated_gif
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def series_to_animated_gif(L, filepath):
imgs = Image(filename=L[0])
for i in L[1:]:
im2 = Image(filename=i)
imgs.sequence.append(im2)
for i in imgs.sequence:
i.delay = 25
imgs.save(filename=filepath)
imgs.close()
print('saved animated.gif')
示例12: cache_blob
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def cache_blob(self, blob_data, checkout_id, filename):
""" Write a blob of data to disk according to the specified
checkout id and filename.
"""
thumbs_dir = "cookbook/assets/img/thumbnails"
new_img = Image(blob=blob_data)
thumb_file = "%s/%s_%s" % (thumbs_dir, checkout_id, filename)
log.info("save thumbnail to: %s", thumb_file)
new_img.save(filename=thumb_file)
示例13: convert_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [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
示例14: save
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def save(self, *args, **kwargs):
super(UploadComics, self).save()
img = Image(filename=self.pdf._get_path(), resolution=200)
img.save(filename=settings.BASE_DIR + '/static_in_env/media_root/images/temp-%s-%s.jpg' % (
self.id, self.name))
comic = Comics.objects.create(general_id=self.id)
for i in range(len(img.sequence)):
image = ComicsImage(image='/media/images/temp-%s-%s-%s.jpg' % (self.id, self.name, i))
image.save()
comic.pages.add(image)
comic.save()
示例15: upload_from_web
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import save [as 别名]
def upload_from_web(self, request, pk=None):
from wand.image import Image
from wand.color import Color
from wand import exceptions as wand_exceptions
from apps.group.models import CourseGroup, CourseGroupMember
chatroom = self.get_object()
try:
chatroom_member = ChatroomMember.objects.get(chatroom=chatroom, user=request.user)
except ChatroomMember.DoesNotExist:
# Create the course group member (is past)
course_group = CourseGroup.objects.get(chatroom=chatroom)
course_group_member = CourseGroupMember.objects.create(course_group=course_group, student=request.user.student, is_past=True)
# Create the chatroom member (is past)
chatroom_member = ChatroomMember.objects.create(user=request.user, chatroom=chatroom, is_past=True)
name = request.data.get('name')
is_anonymous = int(request.data.get('is_anonymous', False))
tag = Tag.objects.get(pk=int(request.POST.get('tag_id')))
new_upload = Upload.objects.create(chatroom_member=chatroom_member, chatroom=chatroom, name=name, tag=tag, is_anonymous=is_anonymous)
all_urls = ""
for fp in request.FILES:
uploadedFile = request.data.get(fp)
if uploadedFile.content_type == "application/pdf":
image_pdf = Image(file=uploadedFile, resolution=250, background=Color("white"))
image_jpeg = image_pdf.convert('jpeg')
count = 0
for single_img in image_jpeg.sequence:
img = Image(image=single_img, resolution=250)
temp = tempfile.TemporaryFile()
img.alpha_channel = False
img.save(file=temp)
url = new_upload.upload_file(temp)
temp.close()
all_urls = all_urls + url + "\n"
count += 1
if count >= 25:
break
break
url = new_upload.upload_file(uploadedFile)
all_urls = all_urls + url + "\n"
activity_type = ChatroomActivityType.objects.get_activity_type(ChatroomActivityTypeManager.UPLOAD)
activity = ChatroomActivity.objects.create(chatroom=chatroom, chatroom_activity_type=activity_type, activity_id=new_upload.pk)
new_upload.send_created_notification(activity, request, True)
# post to slack TODO add detail
message = request.user.email + " uploaded files to " + chatroom.name + ":\n[" + str(new_upload.id) + "] " + all_urls
slack_utils.send_simple_slack_message(message)
return Response(200)