Pack image data for a WM/Picture tag.
346808
def _pack_asf_image(mime, data, type=3, description=""):
    
    tag_data = struct.pack('<bi', type, len(data))
    tag_data += mime.encode("utf-16-le") + b'\x00\x00'
    tag_data += description.encode("utf-16-le") + b'\x00\x00'
    tag_data += data
    return tag_data
66839
def _getImageSize(filename):
    """"""
    result = None
    file = open(filename, 'rb')
    if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
        while 1:
            length, = _struct.unpack('>i', file.read(4))
            chunkID = file.read(4)
            if chunkID == '': # EOF
                break
            if chunkID == b'IHDR':
                # return width, height
                result = _struct.unpack('>ii', file.read(8))
                break
            file.seek(4 + length, 1)
        file.close()
        return result
    file.seek(0)
    if file.read(8) == b'BM': # Bitmap
        file.seek(18, 0) # skip to size data
        result = _struct.unpack('<ii', file.read(8))
    file.close()
    return result
730590
def tag_stuff(self):
        """"""

        # For each packet in the pcap process the contents
        for item in self.input_stream:

            # Make sure it has a tags field (which is a set)
            if 'tags' not in item:
                item['tags'] = set()

            # For each tag_methods run it on the item
            for tag_method in self.tag_methods:
                item['tags'].add(tag_method(item))

            # Not interested in None tags
            if None in item['tags']:
                item['tags'].remove(None)
            # All done
            yield item
747728
def body_block_image_content(tag):
    ""
    image_content = OrderedDict()
    if tag:
        copy_attribute(tag.attrs, 'xlink:href', image_content, 'uri')
        if "uri" in image_content:
            # todo!! alt
            set_if_value(image_content, "alt", "")
    return image_content
345005
def _pack_data(X, Y, metadata):
    
    if not any(metadata):
        # legacy list of list format is acceptable
        return list(zip(X, Y))

    else:
        # newer dictionary-based format is required in order to save metadata
            return [
                {
                    'data': x,
                    'target': y,
                    'metadata': meta
                }
                for x, y, meta in zip(X, Y, metadata)
            ]
723355
def _write_image_description(self):
        """"""
        if (not self._datashape or self._datashape[0] == 1 or
                self._descriptionoffset <= 0):
            return

        colormapped = self._colormap is not None
        if self._imagej:
            isrgb = self._shape[-1] in (3, 4)
            description = imagej_description(
                self._datashape, isrgb, colormapped, **self._metadata)
        else:
            description = json_description(self._datashape, **self._metadata)

        # rewrite description and its length to file
        description = description.encode('utf-8')
        description = description[:self._descriptionlen-1]
        pos = self._fh.tell()
        self._fh.seek(self._descriptionoffset)
        self._fh.write(description)
        self._fh.seek(self._descriptionlenoffset)
        self._fh.write(struct.pack(self._byteorder+self._offsetformat,
                                   len(description)+1))
        self._fh.seek(pos)

        self._descriptionoffset = 0
        self._descriptionlenoffset = 0
        self._descriptionlen = 0
1116426
def image(self, tag, image, step=None):
    
    image = onp.array(image)
    if step is None:
      step = self._step
    else:
      self._step = step
    if len(onp.shape(image)) == 2:
      image = image[:, :, onp.newaxis]
    if onp.shape(image)[-1] == 1:
      image = onp.repeat(image, 3, axis=-1)
    image_strio = io.BytesIO()
    plt.imsave(image_strio, image, format='png')
    image_summary = Summary.Image(
        encoded_image_string=image_strio.getvalue(),
        colorspace=3,
        height=image.shape[0],
        width=image.shape[1])
    summary = Summary(value=[Summary.Value(tag=tag, image=image_summary)])
    self.add_summary(summary, step)
655976
def image_tag(src, options={})
      src = "/images/#{src}" unless src.include? "://" # Add images directory to path if not a full URL
      options[:src] = url_for(src)
      tag(:img, options)
    end
1291262
def map_images_in_tex(tex_files, image_mapping,
                      output_directory, context=False):
    """"""
    extracted_image_data = []
    for tex_file in tex_files:
        # Extract images, captions and labels based on tex file and images
        partly_extracted_image_data = extract_captions(
            tex_file,
            output_directory,
            image_mapping.keys()
        )
        if partly_extracted_image_data:
            # Convert to dict, add proper filepaths and do various cleaning
            cleaned_image_data = prepare_image_data(
                partly_extracted_image_data,
                output_directory,
                image_mapping,
            )
            if context:
                # Using prev. extracted info, get contexts for each image found
                extract_context(tex_file, cleaned_image_data)

            extracted_image_data.extend(cleaned_image_data)

    return extracted_image_data
89095
def _ProcessImage(self, tag, wall_time, step, image):
    """"""
    event = ImageEvent(wall_time=wall_time,
                       step=step,
                       encoded_image_string=image.encoded_image_string,
                       width=image.width,
                       height=image.height)
    self.images.AddItem(tag, event)
862796
def _load_image(cls, rkey):
        """"""

        v = cls._stock[rkey]
        img = None
        itype = v['type']
        if itype in ('stock', 'data'):
            img = tk.PhotoImage(format=v['format'], data=v['data'])
        elif itype == 'created':
            img = v['image']
        else:
            img = tk.PhotoImage(file=v['filename'])
        cls._cached[rkey] = img
        logger.info('Loaded resource %s.' % rkey)
        return img
808222
def _load_data(path, labels_number=1):
  """"""
  with tf.io.gfile.GFile(path, "rb") as f:
    data = f.read()
  offset = 0
  max_offset = len(data) - 1
  while offset < max_offset:
    labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
                           offset=offset).reshape((labels_number,))
    # 1 byte per label, 1024 * 3 = 3072 bytes for the image.
    offset += labels_number
    img = (np.frombuffer(data, dtype=np.uint8, count=3072, offset=offset)
           .reshape((3, _CIFAR_IMAGE_SIZE, _CIFAR_IMAGE_SIZE))
           .transpose((1, 2, 0))
          )
    offset += 3072
    yield labels, img
883684
def pack_data(abi_types, values) -> bytes:
    """"""
    if len(abi_types) != len(values):
        raise ValueError(
            "Length mismatch between provided abi types and values.  Got "
            "{0} types and {1} values.".format(len(abi_types), len(values)),
        )

    normalized_values = map_abi_data([abi_address_to_hex], abi_types, values)

    return decode_hex(''.join(
        remove_0x_prefix(hex_encode_abi_type(abi_type, value))
        for abi_type, value
        in zip(abi_types, normalized_values)
    ))
1147994
def set_tag(self, namespace, repository, tag, image_id):
        """"""
        return self._http_call(self.TAGS + '/' + tag, put, data=image_id,
                               namespace=namespace, repository=repository)
901348
def picture(
        relationshiplist, picname, picdescription, pixelwidth=None,
        pixelheight=None, nochangeaspect=True, nochangearrowheads=True,
        imagefiledict=None):
    
    if imagefiledict is None:
        warn(
            'Using picture() without imagefiledict parameter will be depreca'
            'ted in the future.', PendingDeprecationWarning
        )

    # http://openxmldeveloper.org/articles/462.aspx
    # Create an image. Size may be specified, otherwise it will based on the
    # pixel size of image. Return a paragraph containing the picture

    # Set relationship ID to that of the image or the first available one
    picid = '2'
    picpath = abspath(picname)

    if imagefiledict is not None:
        # Keep track of the image files in a separate dictionary so they don't
        # need to be copied into the template directory
        if picpath not in imagefiledict:
            picrelid = 'rId' + str(len(relationshiplist) + 1)
            imagefiledict[picpath] = picrelid

            relationshiplist.append([
                'http://schemas.openxmlformats.org/officeDocument/2006/relat'
                'ionships/image',
                'media/%s_%s' % (picrelid, basename(picpath))
            ])
        else:
            picrelid = imagefiledict[picpath]
    else:
        # Copy files into template directory for backwards compatibility
        # Images still accumulate in the template directory this way
        picrelid = 'rId' + str(len(relationshiplist) + 1)

        relationshiplist.append([
            'http://schemas.openxmlformats.org/officeDocument/2006/relations'
            'hips/image', 'media/' + picname
        ])

        media_dir = join(template_dir, 'word', 'media')
        if not os.path.isdir(media_dir):
            os.mkdir(media_dir)
        shutil.copyfile(picname, join(media_dir, picname))

    image = Image.open(picpath)

    # Extract EXIF data, if available
    try:
        exif = image._getexif()
        exif = {} if exif is None else exif
    except:
        exif = {}

    imageExif = {}
    for tag, value in exif.items():
        imageExif[TAGS.get(tag, tag)] = value

    imageOrientation = imageExif.get('Orientation', 1)
    imageAngle = {
        1: 0, 2: 0, 3: 180, 4: 0, 5: 90, 6: 90, 7: 270, 8: 270
    }[imageOrientation]
    imageFlipH = 'true' if imageOrientation in (2, 5, 7) else 'false'
    imageFlipV = 'true' if imageOrientation == 4 else 'false'

    # Check if the user has specified a size
    if not pixelwidth or not pixelheight:
        # If not, get info from the picture itself
        pixelwidth, pixelheight = image.size[0:2]

    # Swap width and height if necessary
    if imageOrientation in (5, 6, 7, 8):
        pixelwidth, pixelheight = pixelheight, pixelwidth

    # OpenXML measures on-screen objects in English Metric Units
    # 1cm = 36000 EMUs
    emuperpixel = 12700
    width = str(pixelwidth * emuperpixel)
    height = str(pixelheight * emuperpixel)

    # There are 3 main elements inside a picture
    # 1. The Blipfill - specifies how the image fills the picture area
    #    (stretch, tile, etc.)
    blipfill = makeelement('blipFill', nsprefix='pic')
    blipfill.append(makeelement('blip', nsprefix='a', attrnsprefix='r',
                    attributes={'embed': picrelid}))
    stretch = makeelement('stretch', nsprefix='a')
    stretch.append(makeelement('fillRect', nsprefix='a'))
    blipfill.append(makeelement('srcRect', nsprefix='a'))
    blipfill.append(stretch)

    # 2. The non visual picture properties
    nvpicpr = makeelement('nvPicPr', nsprefix='pic')
    cnvpr = makeelement(
        'cNvPr', nsprefix='pic',
        attributes={'id': '0', 'name': 'Picture 1', 'descr': picdescription}
    )
    nvpicpr.append(cnvpr)
    cnvpicpr = makeelement('cNvPicPr', nsprefix='pic')
    cnvpicpr.append(makeelement(
        'picLocks', nsprefix='a',
        attributes={'noChangeAspect': str(int(nochangeaspect)),
                    'noChangeArrowheads': str(int(nochangearrowheads))}))
    nvpicpr.append(cnvpicpr)

    # 3. The Shape properties
    sppr = makeelement('spPr', nsprefix='pic', attributes={'bwMode': 'auto'})
    xfrm = makeelement(
        'xfrm', nsprefix='a', attributes={
            'rot': str(imageAngle * 60000), 'flipH': imageFlipH,
            'flipV': imageFlipV
        }
    )
    xfrm.append(
        makeelement('off', nsprefix='a', attributes={'x': '0', 'y': '0'})
    )
    xfrm.append(
        makeelement(
            'ext', nsprefix='a', attributes={'cx': width, 'cy': height}
        )
    )
    prstgeom = makeelement(
        'prstGeom', nsprefix='a', attributes={'prst': 'rect'}
    )
    prstgeom.append(makeelement('avLst', nsprefix='a'))
    sppr.append(xfrm)
    sppr.append(prstgeom)

    # Add our 3 parts to the picture element
    pic = makeelement('pic', nsprefix='pic')
    pic.append(nvpicpr)
    pic.append(blipfill)
    pic.append(sppr)

    # Now make the supporting elements
    # The following sequence is just: make element, then add its children
    graphicdata = makeelement(
        'graphicData', nsprefix='a',
        attributes={'uri': ('http://schemas.openxmlformats.org/drawingml/200'
                            '6/picture')})
    graphicdata.append(pic)
    graphic = makeelement('graphic', nsprefix='a')
    graphic.append(graphicdata)

    framelocks = makeelement('graphicFrameLocks', nsprefix='a',
                             attributes={'noChangeAspect': '1'})
    framepr = makeelement('cNvGraphicFramePr', nsprefix='wp')
    framepr.append(framelocks)
    docpr = makeelement('docPr', nsprefix='wp',
                        attributes={'id': picid, 'name': 'Picture 1',
                                    'descr': picdescription})
    effectextent = makeelement('effectExtent', nsprefix='wp',
                               attributes={'l': '25400', 't': '0', 'r': '0',
                                           'b': '0'})
    extent = makeelement('extent', nsprefix='wp',
                         attributes={'cx': width, 'cy': height})
    inline = makeelement('inline', attributes={'distT': "0", 'distB': "0",
                                               'distL': "0", 'distR': "0"},
                         nsprefix='wp')
    inline.append(extent)
    inline.append(effectextent)
    inline.append(docpr)
    inline.append(framepr)
    inline.append(graphic)
    drawing = makeelement('drawing')
    drawing.append(inline)
    run = makeelement('r')
    run.append(drawing)
    paragraph = makeelement('p')
    paragraph.append(run)

    if imagefiledict is not None:
        return relationshiplist, paragraph, imagefiledict
    else:
        return relationshiplist, paragraph
964239
def _pack_bin(self, pix):
        

        r = (pix[0] >> 3) & 0x1F
        g = (pix[1] >> 2) & 0x3F
        b = (pix[2] >> 3) & 0x1F
        bits16 = (r << 11) + (g << 5) + b
        return struct.pack('H', bits16)
615504
def export(self, hashVal=None, hashPath=None, tags=None, galleries=None):
        
        hashVal = hashVal or self.hash
        hashPath = hashPath or self.parent / hashVal + self.ext
        
        source = hashPath.replace('\\', '/').replace(ROOT, '')
        galleries = galleries or []
        tags = tags or []

        imagefile = ROOT / source

        if imagefile.ext == '.psd':
            psd = psd_tools.PSDImage.load(imagefile)
            workImage = psd.as_PIL()
        else:
            workImage = pilImage.open(imagefile)
            self.source = source

        if imagefile.ext in ('.tif', '.tiff', '.psd'):
            png = imagefile.parent / '{}.png'.format(imagefile.namebase)
            workImage.save(png)
            workImage = pilImage.open(png)
            imagefile.move(imagefile.replace(self.hash, self.title))
            self.source = png.replace(ROOT, '')

        formats = [
            ('image', FROG_IMAGE_SIZE_CAP),
            ('small', FROG_IMAGE_SMALL_SIZE),
        ]
        for i, n in enumerate(formats):
            if workImage.size[0] > n[1] or workImage.size[1] > n[1]:
                workImage.thumbnail((n[1], n[1]), pilImage.ANTIALIAS)
                setattr(self, n[0], self.source.name.replace(hashVal, '_' * i + hashVal))
                workImage.save(ROOT + getattr(self, n[0]).name)
            else:
                setattr(self, n[0], self.source)

        self.generateThumbnail()

        for gal in galleries:
            g = Gallery.objects.get(pk=int(gal))
            g.images.add(self)

        self.tagArtist()

        for tagName in tags:
            tag = Tag.objects.get_or_create(name=tagName)[0]
            self.tags.add(tag)

        if not self.guid:
            self.guid = self.getGuid().guid
        self.save()