当前位置: 首页>>代码示例>>Python>>正文


Python Image.format方法代码示例

本文整理汇总了Python中wand.image.Image.format方法的典型用法代码示例。如果您正苦于以下问题:Python Image.format方法的具体用法?Python Image.format怎么用?Python Image.format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在wand.image.Image的用法示例。


在下文中一共展示了Image.format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: convert_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [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
开发者ID:tanghaibao,项目名称:jcvi,代码行数:57,代码来源:grabseeds.py

示例2: appicon

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [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)))
开发者ID:petfactory,项目名称:python,代码行数:28,代码来源:image.py

示例3: make_image_to_post

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [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
开发者ID:RandomOutput,项目名称:CareerNinja,代码行数:34,代码来源:careerNinja.py

示例4: _create_or_update_pdf_thumbnail

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [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)
开发者ID:OpenDevelopmentMekong,项目名称:ckanext-odm_laws,代码行数:37,代码来源:plugin.py

示例5: compose

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def compose(conn, ready_queue, images, config):
    from wand.image import Image
    from wand.color import Color
    import os

    # get all the images and overlay them
    layers = []
    while len(layers) < images:
        try:
            this_config = ready_queue.get()
            layers.append((this_config['name'], this_config))
        except Queue.Empty:
            pass

    # the base to the image we are producing
    base = Image(width=config['width'],
                 height=config['height'],
                 background=Color(config['background']))

    cache = {}

    for name, image_config in sorted(layers):
        x, y, w, h = image_config['area']
        print name, x, y, w, h
        try:
            temp_image = cache[image_config['filename']]
        except KeyError:
            temp_image = Image(filename=image_config['filename'])
            cache[image_config['filename']] = temp_image
        base.composite(temp_image, x, y)

    # save it!
    new_path = 'composite.png'

    for image in cache.values():
        image.close()

    # append a dash and numberal if there is a duplicate
    if os.path.exists(new_path):
        i = 1
        root, ext = os.path.splitext(new_path)
        new_path = "{0}-{1:04d}{2}".format(root, i, ext)
        while os.path.exists(new_path):
            i += 1
            new_path = "{0}-{1:04d}{2}".format(root, i, ext)

    base.format = 'png'
    base.save(filename=new_path)
    base.close()

    conn.send(new_path)
    conn.close()
开发者ID:ikol,项目名称:PURIKURA,代码行数:54,代码来源:composer.py

示例6: flush

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
 def flush(self, filename, scale=100):
     newImage = Image()
     for i in range(self._current_idx):
         newImage.sequence.append(Image(filename="{0}/capture{1}.miff".format(self._tmp_path,\
                                                                              i)))
     newImage.format = 'gif'
     for i, frame in enumerate(newImage.sequence):
         frame.delay = 50
         frame.destroy()
     (newImageWidth, newImageHeight) = newImage.size
     newImage.resize(width=int(scale * newImageWidth / 100),\
                     height=int(scale * newImageHeight / 100))
     newImage.save(filename=filename)
开发者ID:Paulloz,项目名称:enGIF-your-screen,代码行数:15,代码来源:GifOMatic.py

示例7: render_pdf

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
    def render_pdf(self):
        outpdf = PdfFileWriter()
        for page in self.pages:
            if page.extension == "pdf":
                outpdf.addPage(PdfFileReader(StringIO.StringIO(page.binary)).getPage(0))
            else:
                img = Image(blob=page.binary, resolution=72)
                img.format = "jpg"
                img.format = "pdf"
                outpdf.addPage(PdfFileReader(StringIO.StringIO(img.make_blob())).getPage(0))

        pdf_page_buf = StringIO.StringIO()
        outpdf.write(pdf_page_buf)
        return pdf_page_buf.getvalue()
开发者ID:iandennismiller,项目名称:gthnk,代码行数:16,代码来源:day.py

示例8: ExtractImg

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def ExtractImg(pdf_reader, n, out_path):
        writer = PyPDF2.PdfFileWriter()
        page = pdf_reader.getPage(n)
        writer.addPage(page)

        bytes = io.BytesIO()
        writer.write(bytes)
        bytes.seek(0)
	
        wand_img = Image(file = bytes)
	wand_img.format = 'jpg'
	jpg_bin = wand_img.make_blob()

	with open(out_path, 'wb') as temp_file:
		temp_file.write(jpg_bin)
开发者ID:dlv,项目名称:extract_img,代码行数:17,代码来源:extract_img.py

示例9: error_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def error_image(msg, width=420, height=600):
    """Creates an error frontpage"""
    width, height = int(width), int(height)
    img = WandImage(width=width, height=height)
    with Drawing() as draw:
        draw.text_alignment = 'center'
        draw.text(img.width // 2, img.height // 3, msg)
        draw(img)
    background = WandImage(
        width=img.width,
        height=img.height,
        background=Color('white'),
    )
    background.format = 'jpeg'
    background.composite(img, 0, 0)
    return background
开发者ID:universitas,项目名称:tassen,代码行数:18,代码来源:models.py

示例10: normalize_images

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def normalize_images(follower_ids, dest_dir):
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    for profile_id in follower_ids:
        for extn in ['jpg', 'png', 'jpeg']:
            src_file = 'images/'+str(profile_id)+'.'+extn
            dst_file = dest_dir.rstrip('/')+'/'+str(profile_id)+'.jpg'
            if os.path.exists(src_file) and not os.path.exists(dst_file):
                with open(src_file, 'rb') as r:
                    image = Image(blob=r.read())
                    image.format = 'jpg'
                    dim = min(image.width, image.height)
                    dimstr = str(dim)+'x'+str(dim)
                    image.transform(dimstr,'48x48')
                    with open(dst_file,'wb') as o:
                        image.save(o)
开发者ID:MVredenburgh,项目名称:smallbizhackathon,代码行数:18,代码来源:twitter_api.py

示例11: set_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [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()
开发者ID:iandennismiller,项目名称:gthnk,代码行数:21,代码来源:page.py

示例12: pdf_to_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def pdf_to_image(pdf, page=1, size=800, file_format='jpeg', quality=80):
    """Creates a image file from pdf file"""
    try:
        pdf.open()
    except Exception as e:
        raise e
    else:
        # do this while the pdf is open
        reader = PyPDF2.PdfFileReader(pdf, strict=False)
        writer = PyPDF2.PdfFileWriter()
        page_content = reader.getPage(page - 1)
        box = page_content.cropBox
        dims = [float(a - b) for a, b in zip(box.upperRight, box.lowerLeft)]
        scaleby = size / max(dims)
        dims = [int(d * scaleby) for d in dims]
        # resize_page(page_content, size)
        writer.addPage(page_content)
        outputStream = BytesIO()
        writer.write(outputStream)
        outputStream.seek(0)
    finally:
        pdf.close()
    # put content of page in a new image
    foreground = WandImage(
        blob=outputStream,
        format='pdf',
        resolution=int(1.6 * 72 * scaleby),
    )
    # make sure the color space is correct.
    # this prevents an occational bug where rgb colours are inverted
    foreground.type = 'truecolormatte'
    foreground.resize(*dims, 25)
    # white background
    background = WandImage(
        width=foreground.width,
        height=foreground.height,
        background=Color('white')
    )
    background.format = file_format
    background.composite(foreground, 0, 0)
    background.compression_quality = quality
    return background
开发者ID:universitas,项目名称:tassen,代码行数:44,代码来源:models.py

示例13: make_thumbs

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def make_thumbs(source_dir, thumb_dir, thumb_size, thumb_format):

	if os.path.isdir(thumb_dir):
		print('delete dir')
		#input('12')
		shutil.rmtree(thumb_dir)

	os.makedirs(thumb_dir)

	for index, file_name in enumerate(os.listdir(source_dir)):

		img_name, file_ext = os.path.splitext(file_name)
		if file_ext not in ('.jpg', '.jpeg'):
			continue

		img = Image(filename=os.path.join(source_dir, file_name))
		img.resize(thumb_size, thumb_size)

		img.format = thumb_format
		img.save(filename=os.path.join(thumb_dir, '{}_thumb.{}'.format(img_name, thumb_format)))
开发者ID:petfactory,项目名称:python,代码行数:22,代码来源:resize_img.py

示例14: generate

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def generate():
	cmdline = request.form['options'].split(" ")
	cmdline[0] = "../flame";
	process = subprocess.check_output(cmdline, universal_newlines=True);
	try:
		img = Image(filename='static/img/fractal-4.png')
		img.save(filename="static/img/fractal-5.png")
	except:
		pass
	try:
		img = Image(filename='static/img/fractal-3.png')
		img.save(filename="static/img/fractal-4.png")
	except:
		pass
	try:
		img = Image(filename='static/img/fractal-2.png')
		img.save(filename="static/img/fractal-3.png")
	except:
		pass
	try:
		img = Image(filename='static/img/fractal-1.png')
		img.save(filename="static/img/fractal-2.png")
	except:
		pass
	try:
		img = Image(filename='static/img/fractal.png')
		img.save(filename="static/img/fractal-1.png")
	except:
		pass
	try:
		img = Image(filename='/tmp/fractal.tif')
		img.format = "png"
		img.save(filename="static/img/fractal.png")
	except:
		pass
	print(process)
	message="Image generated in " + process.split(" ")[-1] + " / " + cmdline[2] + "T"
	log="Generated image:\t\t" + request.form['options'] + "\n--- Render time:\t" + process.split(" ")[-1] + "--- Number of threads:\t" + cmdline[2] + "\n"
	return jsonify(message=message, log=log)
开发者ID:ItzaPhenix,项目名称:FRACTAL-FLAME,代码行数:41,代码来源:app.py

示例15: favicon

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import format [as 别名]
def favicon():
    if static_favicon:
        return app.send_static_file('favicon.ico')

    # for dynamic fun:
    # width=64&height=64&from=-2hours&graphOnly=true&target=carbon.agents.*.metricsReceived
    favicon_args = {
            'width': 32,
            'height': 32,
            'from': '-2hours',
            'graphOnly': 'true',
            'target': DYNAMIC_FAVICON_TARGET,
            'format': 'png'
            }
    response, headers = upstream_req('/render/', favicon_args)
    response_file = StringIO()
    for data in response():
        response_file.write(data)
    response_file.seek(0)
    image = Image(file=response_file, format='png')
    image.format = 'ico'
    headers['content-type'] = 'image/x-icon'
    return Response(image.make_blob(), headers=headers)
开发者ID:bzed,项目名称:graphite_aclproxy,代码行数:25,代码来源:proxy.py


注:本文中的wand.image.Image.format方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。