本文整理汇总了Python中wand.image.Image.clone方法的典型用法代码示例。如果您正苦于以下问题:Python Image.clone方法的具体用法?Python Image.clone怎么用?Python Image.clone使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wand.image.Image
的用法示例。
在下文中一共展示了Image.clone方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_image_to_post
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def make_image_to_post(self, job_string, image, image_format):
font_size_to_width_ratio = 0.061
font_location = './Gotham-Bold.otf'
fontColors = ['white', 'black']
logging.info(str(datetime.now()) + ': Begin image compositing.')
try:
im = Image(blob=image)
except MissingDelegateError as e:
raise
except:
raise
font_size = im.width * font_size_to_width_ratio
im_clone = im.clone()
im_clone.resize(1,1)
for row in im_clone:
for col in row:
assert isinstance(col, Color)
if (col.red + col.green + col.blue) / 3.0 >= 0.5:
fontColors.reverse()
font = Font(font_location, size=font_size, color=Color(fontColors[1]))
im.caption(job_string, left=7, top=7, width=im.width-10, height=im.height-10, font=font)
font = Font(font_location, size=font_size, color=Color(fontColors[0]))
im.caption(job_string, left=5, top=5, width=im.width-10, height=im.height-10, font=font)
im.format = image_format
return im
示例2: _save_page_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def _save_page_image(pdf_filename, image, thumb_filename,
make_thumb, thumb_size, thread_number, verbose=False):
success = False
image_filename = ''
if True:
#try:
if verbose == True:
print "{0}: Saving off PDF image ...".format(thread_number)
try:
image_filename = '{0}.tiff'.format(pdf_filename)
bg = WandImage(width=image.width, height=image.height, background=Color("white"))
bg.composite(image, 0, 0)
bg.clone().save(
filename = image_filename,
)
except Exception, ex:
print ex
#image.clone().save(
# filename=image_filename
#)
if verbose == True:
print "{0}: Done saving off PDF image.".format(thread_number)
if make_thumb == True:
if verbose == True:
print "{0}: Making thumb nail image: '{1}' ...".format(thread_number, thumb_filename)
FNULL = open(os.devnull, 'w')
cli_call = [
'convert',
'-resize',
'{0}x{0}'.format(thumb_size),
image_filename,
thumb_filename,
]
subprocess.call(
cli_call,
stdout=FNULL,
stderr=subprocess.STDOUT
)
success = True
示例3: main
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def main():
funky_img = Image(filename="../images/funky_illustration.png")
funky_img = resize_to_percent(funky_img, 60)
cropped_img = funky_img.clone()
cropped_img.crop(top=0, left=275, width=340, height=486)
display(funky_img)
display(cropped_img)
示例4: set_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def set_image(self, binary):
self.binary = binary
with Image(blob=self.binary, resolution=150) as img:
self.extension = img.format.lower()
flattened = Image(background=Color("white"),
height=img.height, width=img.width)
flattened.composite(img, left=0, top=0)
flattened.format = "jpeg"
flattened.compression_quality = 50
thumbnail = flattened.clone()
thumbnail.transform(resize='150x200>')
self.thumbnail = thumbnail.make_blob()
preview = flattened.clone()
preview.gaussian_blur(radius=1, sigma=0.5)
preview.transform(resize='612x792>')
self.preview = preview.make_blob()
self.save()
示例5: clone_downscale_save
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def clone_downscale_save(input_file, output_file, pixels=3000000,
width=None, height=None, compression_quality=92):
orig = Image(filename=input_file)
img = orig.clone()
img = downscale(img, pixels, width, height, compression_quality)
# Make sure output directory exists
dirname, _basename = os.path.split(output_file)
mkdir_p(dirname) # Noop if dir already exists
img.save(filename=output_def)
示例6: convert_image
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [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
示例7: main
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def main():
args = parseArguments()
px = args.pixels
out = args.out
filename_out = os.path.splitext(ntpath.basename(args.input))[0] + ".png"
img = Image(filename=args.input, resolution=(72, 72))
img.clone().convert('png').save(filename="xxx.png")
if args.mode is 'android' or args.mode is 'all':
convertImage(img, px, join(out, "drawable-mdpi"), filename_out)
convertImage(img, int(px * 1.5), join(out, "drawable-hdpi"), filename_out)
convertImage(img, px * 2, join(out, "drawable-xhdpi"), filename_out)
convertImage(img, px * 3, join(out, "drawable-xxhdpi"), filename_out)
convertImage(img, px * 4, join(out, "drawable-xxxhdpi"), filename_out)
elif args.mode is 'ios' or args.mode is 'all':
convertImage(img, px * 2, join(out, "ios-2x"), filename_out)
convertImage(img, px, join(out, "ios-1x"), filename_out)
convertImage(img, px * 3, join(out, "ios-3x"), filename_out)
img.close()
示例8: test_wand
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def test_wand():
image_data = Image(blob=s)
image_data.compression_quality = 70
is_gallery_card = False
image_data_size = (image_data.width, image_data.height)
image_size = (720, 720)
if is_gallery_card:
image_size = (720, 1120)
if image_size != image_data_size:
result = image_data.resize(image_size[0], image_size[1])
with image_data.clone() as img:
result = img = crop_image(img, (720, 472))
# 공감전용 카드의 경우 댓글용 이미지를 생성하지 않는다.
if not is_gallery_card:
result = img.resize(460, 310)
result = image_data.resize(360, 360)
result = image_data.resize(132, 132)
return result
示例9: picture_save_api
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def picture_save_api(request_file, original_file_size=(0, 0), original_file_type='jpeg', compress_file_size=(0, 0), compress_file_type='jpeg'):
pic = Picture()
pic.save()
original_image = Image(file=urlopen(request_file))
compress_image = original_image.clone()
original_image.format = original_file_type
compress_image.format = compress_file_type
w, h = original_image.size
original_width = w
compress_width = w
original_height = h
compress_height = h
if original_file_size[0] > 0:
original_width = original_file_size[0]
if original_file_size[1] > 0:
original_height = original_file_size[1]
if compress_file_size[0] > 0:
compress_width = compress_file_size[0]
if compress_file_size[1] > 0:
compress_height = compress_file_size[1]
original_image.resize(original_width, original_height)
original_image.compression_quality = 60
compress_image.resize(compress_width, compress_height)
compress_image.compression_quality = 60
pic.original_image.save(str(pic.id) + u'_o.' + original_file_type, ContentFile(original_image.make_blob()))
pic.compress_image.save(str(pic.id) + u'_c.' + compress_file_type, ContentFile(compress_image.make_blob()))
return pic
示例10: main
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def main():
req_width = 595
req_height = 486
baby_img = Image(filename="baby_cc_sh.png")
baby_img = resize_to_height(baby_img, req_height)
temp_img = new_blank_png(req_width, req_height)
temp_img.composite(baby_img, 0, 0)
baby_img = temp_img
mask_img = new_blank_png(req_width, req_height, color=Color('rgb(32,32,32)'))
mask_img.save(filename="mask_img.png")
print "DEBUG baby_img", baby_img.alpha_channel
print "DEBUG mask_img", mask_img.alpha_channel
baby_img_masked = baby_img.clone()
baby_img_masked.composite_channel(channel='all_channels', image=mask_img, operator='copy_opacity')
display(baby_img)
display(baby_img_masked)
baby_img.save(filename="baby_img.png")
baby_img_masked.save(filename="baby_img_masked.png")
示例11: maps
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
#.........这里部分代码省略.........
domain = "nominatim.openstreetmap.org"
search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search)
#print(domain+search)
conn = http.client.HTTPConnection(domain)
conn.request("GET", search)
r1 = conn.getresponse()
data = r1.read()
conn.close()
except Exception as e:
await self.bot.say("` Error getting GPS data.`")
print("Error getting GPS data.")
print(e)
return
try:
display_name = "-"
soup = BeautifulSoup(data, 'html.parser')
links = soup.findAll('place', lon=True)
results = len(links)
if results == 0:
await self.bot.say("`No results, try to rephrase`")
return
#print("results:\n"+str(results))
#print("display_name:\n"+display_name)
#print("longitude/latitude:\n"+str(longitude)+","+str(latitude))
except Exception as e:
await self.bot.say("`Something went wrong while parsing xml data...`")
print('parse XML failed')
print(e)
return
await self.bot.send_typing(channel)
if results > 1:
list = "```erlang\nResults\n-\n"
index = 0
for link in links:
index += 1
list = list + "(" +str(index) + "): "+ link["display_name"] + "\n"
list = list +"```` Enter result number...`"
await self.bot.say(list)
response = await self.bot.wait_for_message(author=ctx.message.author)
input = response.content.lower().strip()
#Set values for geotiler
input = int(input)-1
place_id = (links[input]["place_id"])
display_name = (links[input]["display_name"])
longitude = (links[input]['lon'])
latitude = (links[input]['lat'])
else:
#Set values for geotiler
place_id = (links[0]["place_id"])
display_name = (links[0]["display_name"])
longitude = (links[0]['lon'])
latitude = (links[0]['lat'])
await self.bot.send_typing(channel)
#print([latitude, longitude, zoomMap])
map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720))
map.extent
image = await geotiler.render_map_async(map)
image.save(MAP)
await self.bot.send_typing(channel)
#Add pointer and text.
savedMap = Image(filename=MAP)
pointer = Image(filename=POINTER)
for o in COMPOSITE_OPERATORS:
w = savedMap.clone()
r = pointer.clone()
with Drawing() as draw:
draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r)
draw(w)
#Text
draw.fill_color = Color("#7289DA")
draw.stroke_color = Color("#5370D7")
draw.stroke_width = 0.2
draw.font_style = 'oblique'
draw.font_size = 32
splitDisplayName = display_name.split(',')
#Object name/number
draw.text(x=20, y=35, body=splitDisplayName[0])
draw(w)
del splitDisplayName[0]
#Print location info on map.
line0 = ""
line1 = ""
draw.font_size = 18
for i in splitDisplayName:
if len(str(line0)) > 30:
line1 = line1 + i + ","
else:
line0 = line0 + i + ","
#line 0
if len(str(line0)) > 2:
draw.text(x=15, y=60, body=line0)
draw(w)
#line 1
if len(str(line1)) > 2:
draw.text(x=15, y=80, body=line1)
draw(w)
w.save(filename=MAP)
await self.bot.send_file(channel, MAP)
示例12: benchmark
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
#.........这里部分代码省略.........
print("")
print("After thumbnail: ", image.size)
print("")
print("save thumb")
step_time = time.time()
#image.save("test.jpg", "JPEG")
square.save("test1.jpg", "JPEG")
print(time.time() - step_time, "seconds")
print("")
print("PIL alternative (total)")
step_time = time.time()
#img = resize_pil_orig(image, (400, 400))
img = resize_pil(image, 400)
print(time.time() - step_time, "seconds")
print("")
img.save("test.jpg", "JPEG")
#shutil.rmtree("sized")
#os.remove("test.jpg")
from wand.image import Image
#0.572014093399 seconds
print("wand open file")
step_time = time.time()
img = Image(filename=source)
print(time.time() - step_time, "seconds")
print("")
print("wand clone image")
step_time = time.time()
clone = img.clone()
print(time.time() - step_time, "seconds")
print("")
print("wand get dimensions")
step_time = time.time()
width = img.width
height = img.height
## with Image(filename=source) as img:
## width = img.width
## height = img.height
print(width, height)
print(time.time() - step_time, "seconds")
print("")
print("wand crop image")
step_time = time.time()
box = calculate_box(img.width, img.height)
img.crop(*box)
print(time.time() - step_time, "seconds")
print("")
print("wand save image")
step_time = time.time()
img.save(filename='temp3.jpg')
print(time.time() - step_time, "seconds")
print("")
#THIS TAKES A *LONG* TIME!!!!
#273.595574856 seconds
#and will only make a difference for certain types of images
#made no difference for one test image
## print "wand liquid rescale"
## step_time = time.time()
## liquid = clone.liquid_rescale(400, 400)
## print time.time() - step_time, "seconds"
## print ""
## print "wand save liquid"
## step_time = time.time()
## img.save(filename='temp-liquid.jpg')
## print time.time() - step_time, "seconds"
## print ""
#0.238882064819 seconds
print("epeg resize")
step_time = time.time()
#TODO
#consider using subprocess...
#any benefits?
#os.system("jhead -cmd \"jpegtran -progressive -rotate %s &i > &o\" %s" % (degrees, self.path))
os.system("epeg -m %s %s temp-epeg.jpg" % (pre_crop, source))
print(time.time() - step_time, "seconds")
print("")
## print "Testing: "
## step_time = time.time()
## print source
## print time.time() - step_time, "seconds"
## print ""
print("TOTAL TIME:")
print(time.time() - start_time, "seconds")
示例13: listdir
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
source_to_augmented = {'/mnt/mass_2x_padding_dataset_train': '/mnt/2x_augmented_train',
'/mnt/mass_2x_padding_dataset_test': '/mnt/2x_augmented_test',
'/mnt/mass_2x_padding_dataset_val': '/mnt/2x_augmented_val'}
# In[198]:
for directory in source_to_augmented:
files = listdir(directory)
N = len(files)
for i, filepath in enumerate(files):
img = Image(filename=directory+'/'+filepath)
[name, ext] = filepath.split('.')
for t in range(5):
z = img.clone()
if t != 0:
rotate(z)
resize_shortest(z)
for tt in range(5):
new_path = '%s/%s_%i_%i.%s' % (source_to_augmented[directory], name, t, tt, ext)
n = z.clone()
random_crop(n)
n.save(filename=new_path)
print 'Done %i/%i' % (i,N)
# In[ ]:
示例14: photowall
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
def photowall(name):
output_final = None
previous_filename = None
#for all the rows,
for row in xrange(LINES):
print "Row ", row
output_row = None
row_width = 0
#concatenate until the image width is reached
img_count = 0
while row_width < WIDTH:
filename = get_next_file() if previous_filename is None else previous_filename
previous_filename = None
print img_count,
if mime is not None:
mimetype = mime.from_file(filename)
if "symbolic link" in mimetype:
filename = os.readlink(filename)
mimetype = mime.from_file(filename)
if not "image" in mimetype:
continue
print "%s: %s" % (filename, mimetype)
else:
try:
print os.readlink(filename)
except OSError:
print filename
img_count += 1
image = Image(filename=filename)
with image.clone() as clone:
factor = float(LINE_HEIGHT)/clone.height
clone.resize(height=LINE_HEIGHT, width=int(clone.width*factor))
#if the new image makes an overflow
if row_width + clone.width > WIDTH:
#compute how many pixels will overflow
overflow = row_width + clone.width - WIDTH
will_fit = clone.width - overflow
if DO_POLAROID and will_fit < MIN_CROP:
row_width = WIDTH
continue
if DO_WRAP:
with clone.clone() as next_img:
next_img.crop(will_fit+1, 0, width=overflow, height=LINE_HEIGHT)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=IMG_FORMAT_SUFFIX)
tmp.close()
next_img.save(filename=tmp.name)
previous_filename = tmp.name
clone.crop(0, 0, width=will_fit, height=LINE_HEIGHT)
if DO_POLAROID:
details = get_file_details(filename)
clone = do_polaroid(clone, details)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=IMG_FORMAT_SUFFIX)
tmp.close()
clone.save(filename=tmp.name)
row_width += clone.width
if output_row is not None:
do_append(output_row.name, tmp.name)
os.unlink(tmp.name)
else:
output_row = tmp
if output_final is not None:
do_append(output_final.name, output_row.name, underneath=True)
os.unlink(output_row.name)
else:
output_final = output_row
final_name = tempfile.gettempdir()+"/"+name+IMG_FORMAT_SUFFIX
os.rename(output_final.name, final_name)
return final_name
示例15: TestImageRoute
# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import clone [as 别名]
class TestImageRoute(FlaskTestCase):
bucket = "wtf"
def setUp(self):
super(TestImageRoute, self).setUp()
with Color('red') as bg:
self.image = Image(width=1920, height=1080, background=bg)
# let's clear the cache
params = OrderedDict()
params['w'] = 100
params['h'] = 100
giraffe.get_file_or_404.invalidate(self.bucket, "redbull.jpg")
giraffe.get_file_with_params_or_404.invalidate(self.bucket,
"redbull.jpg",
"{}/redbull_w100_h100.jpg".format(giraffe.CACHE_DIR),
params,
False)
@mock.patch('giraffe.s3')
def test_image_doesnt_exist(self, s3):
s3.get.side_effect = make_httperror(404)
r = self.app.get("/{}/redbull.jpg".format(self.bucket))
self.assertEqual(r.status_code, 404)
@mock.patch('giraffe.s3')
def test_image_resize_original_doesnt_exist(self, s3):
s3.get.side_effect = make_httperror(404)
r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
self.assertEqual(r.status_code, 404)
def test_image_has_no_extension(self):
r = self.app.get("/{}/foo".format(self.bucket))
self.assertEqual(r.status_code, 404)
def test_bucket_only(self):
r = self.app.get("/{}".format(self.bucket))
self.assertEqual(r.status_code, 404)
# original image as jpeg:
@mock.patch('giraffe.s3')
def test_jpeg_exists(self, s3):
obj = mock.Mock()
obj.content = self.image.make_blob("jpeg")
obj.headers = {'content-type': 'image/jpeg'}
s3.get.return_value = obj
r = self.app.get("/{}/redbull.jpg".format(self.bucket))
self.assertEqual(r.status_code, 200)
content_type = r.headers.get("content-type")
self.assertEqual(content_type, "image/jpeg")
self.assertEqual(Image(blob=r.data).format, 'JPEG')
@mock.patch('giraffe.s3')
def test_jpeg_exists_but_format_as_png(self, s3):
obj = mock.Mock()
obj.content = self.image.make_blob("jpeg")
obj.headers = {'content-type': 'image/jpeg'}
s3.get.side_effect = [obj, make_httperror(404)]
r = self.app.get("/{}/redbull.jpg?fm=png".format(self.bucket))
self.assertEqual(r.status_code, 200)
content_type = r.headers.get("content-type")
self.assertEqual(content_type, "image/png")
args, kwargs = s3.upload.call_args
self.assertEqual(args[0], "giraffe/redbull.png")
self.assertEqual(kwargs['content_type'], "image/png")
self.assertEqual(Image(blob=r.data).format, 'PNG')
@mock.patch('giraffe.s3')
def test_image_exists_but_needs_to_be_resized(self, s3):
obj = mock.Mock()
obj.content = self.image.make_blob("jpeg")
# we'll call s3.get twice, the first time we'll get the original file, the second time
# we'll be calling to check for the specific version of the object.
s3.get.side_effect = [obj, make_httperror(404)]
r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
self.assertEqual(r.status_code, 200)
self.assertEqual(Image(blob=r.data).size, (100, 100))
@mock.patch('giraffe.s3')
def test_image_exists_but_user_wants_unnecessary_resize(self, s3):
obj = mock.Mock()
obj.content = self.image.make_blob("jpeg")
# we'll call s3.get twice, the first time we'll get the original file, the second time
# we'll be calling to check for the specific version of the object.
s3.get.side_effect = [obj, make_httperror(404)]
r = self.app.get("/{}/redbull.jpg?w=1920&h=1080".format(self.bucket))
self.assertEqual(r.status_code, 200)
self.assertEqual(Image(blob=r.data).size, (1920, 1080))
@mock.patch('giraffe.s3')
def test_image_exists_and_has_already_been_resized(self, s3):
obj = mock.Mock()
obj.content = self.image.make_blob("jpeg")
obj2 = mock.Mock()
with self.image.clone() as img:
img.resize(100, 100)
obj2.content = img.make_blob("jpeg")
# we'll call s3.get twice, the first time we'll get the original file, the second time
#.........这里部分代码省略.........