• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.ImageReader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中reportlab.lib.utils.ImageReader的典型用法代码示例。如果您正苦于以下问题:Python ImageReader类的具体用法?Python ImageReader怎么用?Python ImageReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: _image

    def _image(self, node):
        import urllib
        from reportlab.lib.utils import ImageReader

        u = urllib.urlopen(str(node.getAttribute("file")))
        s = StringIO.StringIO()
        s.write(u.read())
        s.seek(0)
        img = ImageReader(s)
        (sx, sy) = img.getSize()

        args = {}
        for tag in ("width", "height", "x", "y"):
            if node.hasAttribute(tag):
                args[tag] = utils.unit_get(node.getAttribute(tag))
        if ("width" in args) and (not "height" in args):
            args["height"] = sy * args["width"] / sx
        elif ("height" in args) and (not "width" in args):
            args["width"] = sx * args["height"] / sy
        elif ("width" in args) and ("height" in args):
            if (float(args["width"]) / args["height"]) > (float(sx) > sy):
                args["width"] = sx * args["height"] / sy
            else:
                args["height"] = sy * args["width"] / sx
        self.canvas.drawImage(img, **args)
开发者ID:jordotech,项目名称:trml2pdf,代码行数:25,代码来源:trml2pdf.py


示例2: _image

    def _image(self, node):
        import urllib
        from reportlab.lib.utils import ImageReader
        u = urllib.urlopen(str(node.getAttribute('file')))
        s = StringIO.StringIO()
        s.write(u.read())
        s.seek(0)
        img = ImageReader(s)
        (sx,sy) = img.getSize()

        args = {}
        for tag in ('width','height','x','y'):
            if node.hasAttribute(tag):
                args[tag] = utils.unit_get(node.getAttribute(tag))
                
        if node.hasAttribute("preserveAspectRatio"):
            args["preserveAspectRatio"] = True
        if node.hasAttribute("mask"):
            args["mask"] = node.getAttribute("mask")
        if node.hasAttribute("anchor"):
            args["anchor"] = node.getAttribute("anchor")
        if ('width' in args) and (not 'height' in args):
            args['height'] = sy * args['width'] / sx
        elif ('height' in args) and (not 'width' in args):
            args['width'] = sx * args['height'] / sy
        elif ('width' in args) and ('height' in args) and (not args.get("preserveAspectRatio", False)):
            #if (float(args['width'])/args['height'])>(float(sx)>sy):
            #    args['width'] = sx * args['height'] / sy
            #else:
            #    args['height'] = sy * args['width'] / sx
            pass
        self.canvas.drawImage(img, **args)
开发者ID:japostoles,项目名称:trml2pdf,代码行数:32,代码来源:trml2pdf.py


示例3: main

def main():
    if len(sys.argv) < 2:
        print("Syntax: {0} <Image Directory> <Output File>".format(__file__))
        return 1
    image_dir = sys.argv[1]
    output_file = sys.argv[2]
    if not output_file.endswith(".pdf"):
        output_file += ".pdf"

    file_list = []
    for filename in os.listdir(image_dir):
        if len(filename) >= 4 and filename[-4:] in ALLOWED_EXTENSIONS:
            file_list.append(os.path.join(image_dir, filename))

    print("Make a PDF slide at {0} from images in the following order:".format(output_file))
    pdf = canvas.Canvas(output_file, pageCompression=True)
    for i, filepath in enumerate(sorted(file_list)):
        print("[{2}/{1}] {0}".format(filepath,
                                     len(file_list),
                                     i+1))
        image = ImageReader(filepath)
        pdf.setPageSize(image.getSize())
        pdf.drawImage(image, 0, 0)
        pdf.showPage()
    pdf.save()
开发者ID:mrcuongnv,项目名称:Image2Slide,代码行数:25,代码来源:images2slide.py


示例4: makeRawImage

def makeRawImage(filename,IMG=None,detectJpeg=False):
    import zlib
    img = ImageReader(filename)
    if IMG is not None:
        IMG.append(img)
        if detectJpeg and img.jpeg_fh():
            return None

    imgwidth, imgheight = img.getSize()
    raw = img.getRGBData()

    code = []
    append = code.append
    # this describes what is in the image itself
    append('BI')
    append('/W %s /H %s /BPC 8 /CS /%s /F [/Fl]' % (imgwidth, imgheight,_mode2cs[img.mode]))
    append('ID')
    #use a flate filter
    assert len(raw) == imgwidth * imgheight*_mode2bpp[img.mode], "Wrong amount of data for image"
    compressed = zlib.compress(raw)   #this bit is very fast...

    #append in blocks of 60 characters
    _chunker(compressed,code)

    append('EI')
    return code
开发者ID:AlonsoAyelen,项目名称:Voluntariado_veterinaria,代码行数:26,代码来源:pdfutils.py


示例5: _image

    def _image(self, node):
        from six.moves import urllib

        from reportlab.lib.utils import ImageReader
        u = urllib.request.urlopen("file:" + str(node.getAttribute('file')))
        s = io.BytesIO()
        s.write(u.read())
        s.seek(0)
        img = ImageReader(s)
        (sx, sy) = img.getSize()

        args = {}
        for tag in ('width', 'height', 'x', 'y'):
            if node.hasAttribute(tag):
                # if not utils.unit_get(node.getAttribute(tag)):
                #     continue
                args[tag] = utils.unit_get(node.getAttribute(tag))

        if node.hasAttribute("preserveAspectRatio"):
            args["preserveAspectRatio"] = True
        if node.hasAttribute('mask'):
            args['mask'] = node.getAttribute('mask')
        if ('width' in args) and ('height' not in args):
            args['height'] = sy * args['width'] / sx
        elif ('height' in args) and ('width' not in args):
            args['width'] = sx * args['height'] / sy
        elif ('width' in args) and ('height' in args) and (not args.get("preserveAspectRatio", False)):
            if (float(args['width']) / args['height']) > (float(sx) > sy):
                args['width'] = sx * args['height'] / sy
            else:
                args['height'] = sy * args['width'] / sx
        self.canvas.drawImage(img, **args)
开发者ID:daemondazz,项目名称:trml2pdf,代码行数:32,代码来源:trml2pdf.py


示例6: convertPDF

def convertPDF(chapter_num, series_name):
    try:
        n = 1
        for dirpath, dirnames, filenames in os.walk("ROOT_PATH"):
            PdfOutputFileName = "chapter" + str(chapter_num) + ".pdf"
            c = canvas.Canvas(PdfOutputFileName)
            if n == 1:
                filenames = sorted([name for name in filenames if name.endswith(".jpg")], key=pageNum)
                for filename in filenames:
                    print "evaluating file name " + filename
                    LowerCaseFileName = filename.lower()
                    if LowerCaseFileName.endswith(".jpg"):
                        filepath = os.path.join(dirpath, filename)
                        print "found page " + filename
                        im = ImageReader(filepath)
                        imagesize = im.getSize()
                        c.setPageSize(imagesize)
                        c.drawImage(filepath, 0, 0)
                        c.showPage()
                        c.save()
                        try:
                            os.remove(filepath)
                        except WindowsError as e:
                            print e
            n = n + 1
            print "PDF created " + PdfOutputFileName
    except:
        raise
开发者ID:jennypeng,项目名称:MangaScrape,代码行数:28,代码来源:scraper.py


示例7: resolve_image

    def resolve_image(self, node):
        # Get filename from image node attribute file
        filename = str(node.getAttribute('file'))

        # Try resolving filename from image resource directories
        try:
            path = find_resource_abspath(filename, self.image_dirs)
        except ValueError:
            # On fail, return None
            return None, None

        # Open the file on the image reader
        fd = file(path, "r")
        img = ImageReader(fd)

        (sx, sy) = img.getSize()
        args = {}
        for tag in ('width', 'height', 'x', 'y'):
            if node.hasAttribute(tag):
                args[tag] = t2putils.as_pt(node.getAttribute(tag))
        if ('width' in args) and (not 'height' in args):
            args['height'] = sy * args['width'] / sx
        elif ('height' in args) and (not 'width' in args):
            args['width'] = sx * args['height'] / sy
        elif ('width' in args) and ('height' in args):
            if (float(args['width'])/args['height'])>(float(sx)>sy):
                args['width'] = sx * args['height'] / sy
            else:
                args['height'] = sy * args['width'] / sx
        return img, args
开发者ID:whosaysni,项目名称:template2pdf,代码行数:30,代码来源:utils.py


示例8: process_text

 def process_text(node,new_node):
     if new_node.tag in ['story','tr','section']:
         new_node.attrib.clear()
     for child in utils._child_get(node, self):
         new_child = copy.deepcopy(child)
         new_node.append(new_child)
         if len(child):
             for n in new_child:
                 new_child.text  = utils._process_text(self, child.text)
                 new_child.tail  = utils._process_text(self, child.tail)
                 new_child.remove(n)
             process_text(child, new_child)
         else:
             if new_child.tag=='img' and new_child.get('name'):
                 if _regex.findall(new_child.get('name')) :
                     src =  utils._process_text(self, new_child.get('name'))
                     if src :
                         new_child.set('src','data:image/gif;base64,%s'%src)
                         output = cStringIO.StringIO(base64.decodestring(src))
                         img = ImageReader(output)
                         (width,height) = img.getSize()
                         if not new_child.get('width'):
                             new_child.set('width',str(width))
                         if not new_child.get('height') :
                             new_child.set('height',str(height))
                     else :
                         new_child.getparent().remove(new_child)
             new_child.text  = utils._process_text(self, child.text)
             new_child.tail  = utils._process_text(self, child.tail)
开发者ID:ccdos,项目名称:OpenERP,代码行数:29,代码来源:html2html.py


示例9: _image

 def _image(self, node):
     #add attribute 'src' to tag 'image' by xiandong.xie
     s = StringIO.StringIO()
     if node.hasAttribute('src'):
         import base64
         imgdata = base64.b64decode(node.getAttribute('src'))
         s.write(imgdata)
     else:
         import urllib
         u = urllib.urlopen(str(node.getAttribute('file')))
         s.write(u.read())
     from reportlab.lib.utils import ImageReader
     s.seek(0)
     img = ImageReader(s)
     
     (sx,sy) = img.getSize()
     
     args = {}
     for tag in ('width','height','x','y'):
         if node.hasAttribute(tag):
             args[tag] = utils.unit_get(node.getAttribute(tag))
     if ('width' in args) and (not 'height' in args):
         args['height'] = sy * args['width'] / sx
     elif ('height' in args) and (not 'width' in args):
         args['width'] = sx * args['height'] / sy
     elif ('width' in args) and ('height' in args):
         if (float(args['width'])/args['height'])>(float(sx)>sy):
             args['width'] = sx * args['height'] / sy
         else:
             args['height'] = sy * args['width'] / sx
     self.canvas.drawImage(img, **args)
开发者ID:jbetsinger,项目名称:mes,代码行数:31,代码来源:trml2pdf.py


示例10: _image

    def _image(self, node):
        import urllib
        from reportlab.lib.utils import ImageReader
        u = urllib.urlopen(str(node.getAttribute('file')))
        s = StringIO.StringIO()
        s.write(u.read())
        s.seek(0)
        img = ImageReader(s)
        (sx,sy) = img.getSize()

        args = {}
        for tag in ('width','height','x','y'):
            if node.hasAttribute(tag):
                if not utils.unit_get(node.getAttribute(tag)):
                    continue
                args[tag] = utils.unit_get(node.getAttribute(tag))
        if ('width' in args) and (not 'height' in args):
            args['height'] = sy * args['width'] / sx
        elif ('height' in args) and (not 'width' in args):
            args['width'] = sx * args['height'] / sy
        elif ('width' in args) and ('height' in args):
            if (float(args['width'])/args['height'])>(float(sx)>sy):
                args['width'] = sx * args['height'] / sy
            else:
                args['height'] = sy * args['width'] / sx
        self.canvas.drawImage(img, **args)
开发者ID:joeyates,项目名称:trml2pdf,代码行数:26,代码来源:trml2pdf.py


示例11: _create_header

def _create_header(canvas, doc, draw_page_number=True):
    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y = PAGE_HEIGHT - HEADER_MARGIN

    canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'DEPARTMENT OF PARKS AND WILDLIFE')

    current_y -= 30

    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    canvas.drawImage(dpaw_header_logo, HEADER_MARGIN, current_y - dpaw_header_logo_size[1])

    current_x = HEADER_MARGIN + dpaw_header_logo_size[0] + 5

    canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE)

    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), 'Enquiries:')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Telephone:')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Facsimile:')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Web Site:')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Correspondance:')

    current_x += 80

    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      '17 DICK PERRY AVE, KENSINGTON, WESTERN AUSTRALIA')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, '08 9219 9000')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, '08 9219 8242')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, doc.site_url)

    canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Locked Bag 30')
    canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
                      'Bentley Delivery Centre WA 6983')

    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y -= 36
    current_x += 200

    if draw_page_number:
        canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER), 'PAGE')

    if hasattr(doc, 'licence') and doc.licence.licence_number is not None and doc.licence.licence_sequence:
        canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'NO.')

    canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE)

    current_x += 50

    if draw_page_number:
        canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER), str(canvas.getPageNumber()))

    if hasattr(doc, 'licence') and doc.licence.licence_number is not None and doc.licence.licence_sequence:
        canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                          '%s-%d' % (doc.licence.licence_number, doc.licence.licence_sequence))
开发者ID:serge-gaia,项目名称:ledger,代码行数:57,代码来源:pdf.py


示例12: test

    def test(self):
        import reportlab.test
        from reportlab.lib.utils import rl_isfile
        imageFileName = os.path.dirname(reportlab.test.__file__) + os.sep + 'pythonpowered.gif'
        assert rl_isfile(imageFileName), "%s not found!" % imageFileName

        ir = ImageReader(imageFileName)
        assert ir.getSize() == (110,44)
        pixels = ir.getRGBData()
        assert md5.md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
开发者ID:eaudeweb,项目名称:naaya,代码行数:10,代码来源:test_images.py


示例13: render

 def render(self, canvas):
     if os.path.isfile(self.link):
         im = ImageReader(self.link)
         #pdb.set_trace()
         size = int(self.height/mm*2.8)
         hh = size
         ww = int(im.getSize()[0]*hh/im.getSize()[1])
         #im.thumbnail((size, size))
         canvas.drawImage(im, self.position[0], self.position[1], ww, hh)
     else:
         print "File", self.link, "not found."
开发者ID:aroche,项目名称:pySequoia,代码行数:11,代码来源:abstractLab.py


示例14: pdf

    def pdf(self,REQUEST): 
            """
   	    Test
            """
            skin = self.portal_skins.invoicing_templates
            showTemplate=skin.showIssue
	    output = StringIO()
	    c = canvas.Canvas(output,pagesize=letter,bottomup=0)
	    x=35
	    y=50
	    theImage=self.getPicture()
	    theImageData = StringIO()
	    theImageUsage = theImage.file._read_data(theImageData)
	    theImageReader = ImageReader(theImageUsage)
	    (width,height) = theImageReader.getSize()
            parent = self.aq_inner.aq_parent
            width = self.getWidth()
            height = self.getHeight()
	    if self.getTopMargin():
		y+=15
	    c.drawImage(theImageReader,x,y,width,height,anchor='ne')
	    caption = self.getCaption()
	    credit = self.getCredit()
	    pdfmetrics.registerFont(TTFont('FilosBold','FilosBol.ttf'))
	    pdfmetrics.registerFont(TTFont('FilosReg','FilosReg.ttf'))
	    if caption is not None:
	        textobject = c.beginText()
		h = self.getHeight()
		if h is None:
			h = 400
	        textobject.setTextOrigin(x,y+h+30)
	        fontsize = 14
	        textobject.setFont("FilosReg", fontsize)
	        textobject.textLine(caption)
	        c.drawText(textobject)
            if credit is not None:
                textobject = c.beginText()
                h = self.getHeight()
                if h is None:
                    h = 400
                w = self.getWidth()
                w = w - 100
                textobject.setTextOrigin(x-w,y+h+15)
                fontsize = 11
                textobject.setFont("FilosReg",fontsize)
                textobject.textLine(credit)
                c.drawText(textobject)
	    c.showPage()
	    c.save()
	    result = output.getvalue()
	    output.close()
	    response = REQUEST.RESPONSE
            response.setHeader('Content-type','application/pdf')
	    return result 
开发者ID:newhollandpress,项目名称:newspaper,代码行数:54,代码来源:Pix.py


示例15: draw_image

	def draw_image(self, image, alpha_channel=None):
		if not image: return
		if self.colorspace == uc2const.COLOR_CMYK:
			image = self.cms.convert_image(image, uc2const.IMAGE_CMYK)
		elif self.colorspace == uc2const.COLOR_RGB:
			image = self.cms.convert_image(image, uc2const.IMAGE_RGB)
		elif self.colorspace == uc2const.COLOR_GRAY:
			image = self.cms.convert_image(image, uc2const.IMAGE_GRAY)
		img = ImageReader(image)
		img.getRGBData()
		if alpha_channel: img._dataA = ImageReader(alpha_channel)
		self.canvas.drawImage(img, 0, 0, mask='auto')
开发者ID:sk1project,项目名称:sk1-wx,代码行数:12,代码来源:pdfgen.py


示例16: get_image

 def get_image(self, game, path, width=1*cm, height=None):
     """
     Create an image from a path - either on on disc or from a web URL.
     """
     if self.progress:
         print "Retrieving image for game: %7d" % int(game.id)
     img = ImageReader(path)
     iw, ih = img.getSize()
     aspect = ih / float(iw)
     if height:
         return Image(path, width=(height * aspect), height=height)
     else:
         return Image(path, width=width, height=(width * aspect))
开发者ID:gamesbook,项目名称:gamereporter,代码行数:13,代码来源:report_builder.py


示例17: __init__

    def __init__(self, fileName,ident=None):
        # check if the file is remote, if so, download it to a temporary file and reset fileName
        self._isRemote = _getIsRemote(fileName)
        if self._isRemote:
            fileName, self._format = _getRemoteFile(fileName) 
        else: 
            self._format = _getFormat(fileName)
        
        if self._format != 'jpg':
            raise IllegalFormat(fileName, 'JPG')        


        ImageReader.__init__(self, fileName, ident)
开发者ID:MobileWebApps,项目名称:splunk-search-tools-app,代码行数:13,代码来源:image_utils.py


示例18: image

  def image(self, filename, width=None, height=None, left=0, bottom=0, top=None, right=None, mask=None, preserveAspectRatio=False, anchor='c'):
    ''' add an image to canvas '''
    
    self.saveState()
    image  = ImageReader(filename)
    width  = image.getSize()[0] if width==None  else width
    height = image.getSize()[1] if height==None else height
    
    width  = checkPercent(width, self.width)
    height = checkPercent(height, self.height)

    x, y = self.placement(width, height, left, bottom, top, right)
    self.drawImage(image, x, y, width, height, mask, preserveAspectRatio, anchor)
    self.restoreState()
开发者ID:karlpilkington,项目名称:reportlab-wrapper,代码行数:14,代码来源:wrapper.py


示例19: Image

class Image(SimpleChunk):
    """An image."""

    def __init__(self, filename, zoom=100, raised_by=0):
        self.filename = filename
        self.zoom = zoom
        self.raised_by = raised_by
        self.image = ImageReader(filename)

    def size(self, canvas, w, h):
        myw, myh = self.image.getSize()
        myw = myw * self.zoom / 100
        myh = myh * self.zoom / 100
        return myw, myh

    def drawOn(self, canvas, x, y, w, h):
        myw, myh = self.size(canvas, w, h)
        raised_by = self.raised_by * myh / 100
        try:
            canvas.drawImage(self.filename, x, y - myh + raised_by, myw, myh,
                             mask='auto')
        except Exception:
            log.debug("Exception in canvas.drawImage:", exc_info=True)
            log.warning("Could not render image %s", self.filename)

        return x + myw, y

    def __str__(self):
        return '[%s]' % self.filename
开发者ID:mgedmin,项目名称:mgp2pdf,代码行数:29,代码来源:mgp2pdf.py


示例20: callPDFPDTBySameName

    def callPDFPDTBySameName(self,c,x,y,REQUEST,parent,top,pagenumber):
	    """
	    Test
	    """
	    y = 1200 - y
	    self.left = x
	    self.top = y
            print self.Title()
	    self.pagenumber=pagenumber
            skinTool = getToolByName(self, 'portal_skins')
	    items = self.listFolderContents(contentFilter={"portal_type":"Advertizement"})
	    for ad in items:
		theImage = ad.getImage()
	        thePress = ImageReader(StringIO(str(theImage.data)))
		(width,height) = thePress.getSize()
	        c.drawImage(thePress,x,y,width,height)
	    return (x,y)
开发者ID:newhollandpress,项目名称:newspaper,代码行数:17,代码来源:Company.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pdfmetrics.getFont函数代码示例发布时间:2022-05-26
下一篇:
Python utils.rl_isfile函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap