本文整理汇总了Python中wand.image.Image方法的典型用法代码示例。如果您正苦于以下问题:Python image.Image方法的具体用法?Python image.Image怎么用?Python image.Image使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wand.image
的用法示例。
在下文中一共展示了image.Image方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_convert
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def _run_convert(filename, page, res=120):
idx = page + 1
temp_time = time.time() * 1000
# 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存
pdfile = getPdfReader(filename)
pageObj = pdfile.getPage(page)
dst_pdf = PdfFileWriter()
dst_pdf.addPage(pageObj)
pdf_bytes = io.BytesIO()
dst_pdf.write(pdf_bytes)
pdf_bytes.seek(0)
img = Image(file=pdf_bytes, resolution=res)
img.format = 'png'
img.compression_quality = 90
img.background_color = Color("white")
# 保存图片
img_path = '%s%d.png' % (filename[:filename.rindex('.')], idx)
img.save(filename=img_path)
img.destroy()
img = None
pdf_bytes = None
dst_pdf = None
print('convert page %d cost time %d' % (idx, (time.time() * 1000 - temp_time)))
示例2: pdf_preview
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def pdf_preview(tmp_file_path, tmp_dir):
if use_generic_pdf_cover:
return None
try:
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg"
with Image() as img:
img.options["pdf:use-cropbox"] = "true"
img.read(filename=tmp_file_path + '[0]', resolution=150)
img.compression_quality = 88
img.save(filename=os.path.join(tmp_dir, cover_file_name))
return cover_file_name
except PolicyError as ex:
log.warning('Pdf extraction forbidden by Imagemagick policy: %s', ex)
return None
except Exception as ex:
log.warning('Cannot extract cover image, using default: %s', ex)
return None
示例3: save_image
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def save_image(pdf_path, img_path, page_num):
"""
Creates images for a page of the input pdf document and saves it
at img_path.
:param pdf_path: path to pdf to create images for.
:param img_path: path where to save the images.
:param page_num: page number to create image from in the pdf file.
:return:
"""
pdf_img = Image(filename="{}[{}]".format(pdf_path, page_num))
with pdf_img.convert("png") as converted:
# Set white background.
converted.background_color = Color("white")
converted.alpha_channel = "remove"
converted.save(filename=img_path)
示例4: convert_webp_to_png
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def convert_webp_to_png(webp_file: [str, BytesIO], png_file: str) -> bool:
"""
copied from EH Forwarder Bot
:param webp_file: full path or BytesIO
:param png_file: full output path
:return:
"""
if isinstance(webp_file, str):
input_file = webp_file
else:
input_file = '/tmp/' + str(uuid4()) + '.webp'
f = open(input_file, 'wb')
f.write(webp_file.read())
f.close()
logger.debug(f"converting webp to {png_file}")
img = WandImage(filename=input_file)
img.save(filename=png_file)
os.remove(input_file)
示例5: set_data
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def set_data(self, data):
""" Set the data for this attachment from a file-like object. """
if self.mimetype == PDF:
if self.id is None:
db.session.add(self)
db.session.flush()
# save pdf to s3
filename = '%d/%s' % (self.id, self.filename)
current_store.put_file(data, 'document-attachment', filename, 0, 0, self.mimetype, False)
data.seek(0)
# convert to an image for use with thumbnails
self.log.info("Converting PDF to image")
with WandImage(file=data, resolution=300) as img:
img.format = 'png'
data = StringIO()
img.save(file=data)
data.seek(0)
self.log.info("Converted")
self.image.from_file(data)
db.session.flush()
self.generate_thumbnails()
示例6: render_chart
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def render_chart(pdf_file, page, bounds, dpi, target):
"""Renders part of a pdf file with imagemagick.
Pass this function the bounds and resolution.
"""
pdf_page = pdf_file + '[{}]'.format(page)
with Image(filename=pdf_page, resolution=dpi) as img:
factor = 1.0*dpi/100
x0 = bounds[0]
y0 = bounds[1]
w = bounds[2] - x0
h = bounds[3] - y0
img.crop(left=int(x0*factor), top=int(y0*factor),
width=int(w*factor), height=int(h*factor))
# put transparent image on white background
with Image(width=img.width, height=img.height,
background=Color("white")) as bg:
bg.composite(img, 0, 0)
bg.save(filename=target)
示例7: setup
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def setup(bot):
global geotiler
global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS
global BeautifulSoup
check_folders()
check_files()
try:
import geotiler
except:
raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.")
try:
from bs4 import BeautifulSoup
except:
raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.")
try:
from wand.image import Image, COMPOSITE_OPERATORS
from wand.drawing import Drawing
from wand.display import display
from wand.image import Image
from wand.color import Color
except:
raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html")
bot.add_cog(OpenStreetMaps(bot))
示例8: get_versions
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def get_versions():
if not use_generic_pdf_cover:
IVersion = ImageVersion.MAGICK_VERSION
WVersion = ImageVersion.VERSION
else:
IVersion = u'not installed'
WVersion = u'not installed'
if use_pdf_meta:
PVersion='v'+PyPdfVersion
else:
PVersion=u'not installed'
if lxmlversion:
XVersion = 'v'+'.'.join(map(str, lxmlversion))
else:
XVersion = u'not installed'
if use_PIL:
PILVersion = 'v' + PILversion
else:
PILVersion = u'not installed'
if comic.use_comic_meta:
ComicVersion = comic.comic_version or u'installed'
else:
ComicVersion = u'not installed'
return {'Image Magick': IVersion,
'PyPdf': PVersion,
'lxml':XVersion,
'Wand': WVersion,
'Pillow': PILVersion,
'Comic_API': ComicVersion}
示例9: zoom_blur
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def zoom_blur(x, severity=1):
c = [np.arange(1, 1.11, 0.01),
np.arange(1, 1.16, 0.01),
np.arange(1, 1.21, 0.02),
np.arange(1, 1.26, 0.02),
np.arange(1, 1.31, 0.03)][severity - 1]
x = (np.array(x) / 255.).astype(np.float32)
out = np.zeros_like(x)
for zoom_factor in c:
out += clipped_zoom(x, zoom_factor)
x = (x + out) / (len(c) + 1)
return np.clip(x, 0, 1) * 255
# def barrel(x, severity=1):
# c = [(0,0.03,0.03), (0.05,0.05,0.05), (0.1,0.1,0.1),
# (0.2,0.2,0.2), (0.1,0.3,0.6)][severity - 1]
#
# output = BytesIO()
# x.save(output, format='PNG')
#
# x = WandImage(blob=output.getvalue())
# x.distort('barrel', c)
#
# x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),
# cv2.IMREAD_UNCHANGED)
#
# if x.shape != (224, 224):
# return np.clip(x[..., [2, 1, 0]], 0, 255) # BGR to RGB
# else: # greyscale to RGB
# return np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255)
示例10: test_set_up
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def test_set_up(self):
def assert_valid_eps_file(test_file_path):
self.assertTrue(os.path.isfile(test_file_path))
self.assertEqual(Image(filename=test_file_path).size, (100, 100))
self.assertEqual(Image(filename=test_file_path).format, "EPT")
for i in range(1, 3):
assert_valid_eps_file(
os.path.join(self.converter_tests_resource_path, "convert_test", "test-0" + str(i) + ".eps"))
assert_valid_eps_file(
os.path.join(self.converter_tests_resource_path, "convert_test", "subfolder", "test-04.eps"))
assert_valid_eps_file(
os.path.join(self.converter_tests_resource_path, "convert_test", "subfolder", "subsubfolder",
"test-05.eps"))
示例11: assert_valid_png_file
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def assert_valid_png_file(self, test_file_path, size):
self.assertTrue(os.path.isfile(test_file_path))
self.assertEqual(Image(filename=test_file_path).size, size)
self.assertEqual(Image(filename=test_file_path).format, "PNG")
示例12: process
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def process(self, pdf_filename, pdf_resolution, imageformat, do_orientation):
final_text = ""
image_pdf = Image(filename=pdf_filename, resolution=pdf_resolution)
image_page = image_pdf.convert(imageformat)
page = 1
process_start = time.time()
for img in image_page.sequence:
img_per_page = Image(image=img)
img_per_page.type = 'grayscale'
img_per_page.depth = 8
img_per_page.density = pdf_resolution
try:
img_per_page.level(black=0.3, white=1.0, gamma=1.5, channel=None)
except AttributeError as e:
print("Update Wand library: %s" % e)
img_per_page.save(filename="buffer.png")
page_start = time.time()
txt = self.image2txt_pyocr(img_per_page.make_blob(imageformat), do_orientation)
page_elaboration = time.time() - page_start
print("page %s - size %s - process %2d sec. - text %s" %
(page, img_per_page.size, page_elaboration, len(txt)))
final_text += "%s\n" % txt
page += 1
img.destroy()
process_end = time.time() - process_start
print("Total elaboration time: %s" % process_end)
return final_text
示例13: worker_convert
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def worker_convert(self, f_input, f_output):
source = Image(filename=f_input)
destination = source.convert(self.imageformat)
destination.save(filename=f_output)
os.remove(f_input)
print('%s => %s' % (f_input, f_output))
示例14: _resize_image
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def _resize_image(path, width, height):
filename_without_extension, extension = os.path.splitext(path)
with Image(filename=path) as src:
img = src.clone()
current_aspect_ratio = img.width / img.height
if not width:
width = int(current_aspect_ratio * height)
if not height:
height = int(width / current_aspect_ratio)
desired_aspect_ratio = width / height
# Crop the image to fit the desired AR
if desired_aspect_ratio > current_aspect_ratio:
newheight = int(img.width / desired_aspect_ratio)
img.crop(
0,
int((img.height / 2) - (newheight / 2)),
width=img.width,
height=newheight,
)
else:
newwidth = int(img.height * desired_aspect_ratio)
img.crop(
int((img.width / 2) - (newwidth / 2)), 0, width=newwidth, height=img.height,
)
img.resize(width, height)
return img
示例15: upload_image
# 需要导入模块: from wand import image [as 别名]
# 或者: from wand.image import Image [as 别名]
def upload_image():
_clear_imagemagick_temp_files()
if "file" not in request.files:
return jsonify(error="File is missing!"), 400
file = request.files["file"]
random_string = _get_random_filename()
tmp_filepath = os.path.join("/tmp/", random_string)
file.save(tmp_filepath)
output_type = settings.OUTPUT_TYPE or filetype.guess_extension(tmp_filepath)
error = None
output_filename = os.path.basename(tmp_filepath) + f".{output_type}"
output_path = os.path.join(settings.IMAGES_DIR, output_filename)
try:
with Image(filename=tmp_filepath) as img:
img.strip()
if output_type not in ["gif"]:
with img.sequence[0] as first_frame:
with Image(image=first_frame) as first_frame_img:
with first_frame_img.convert(output_type) as converted:
converted.save(filename=output_path)
else:
with img.convert(output_type) as converted:
converted.save(filename=output_path)
except MissingDelegateError:
error = "Invalid Filetype"
finally:
if os.path.exists(tmp_filepath):
os.remove(tmp_filepath)
if error:
return jsonify(error=error), 400
return jsonify(filename=output_filename)