Unpack and Squash image to local filesystem
771104
def unpack(destdir):
    """"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        anchore_print("Unpacking images: " + ' '.join(nav.get_images()))
        result = nav.unpack(destdir=destdir)
        if not result:
            anchore_print_err("no images unpacked")
            ecode = 1
        else:
            for imageId in result:
                anchore_print("Unpacked image: " + imageId)
                anchore_print("Unpack directory: "+ result[imageId])
    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    
    sys.exit(ecode)
159760
def from_image(cls, image, filename):
        

        source = Image.open(BytesIO(image))
        source = source.convert('1')
        width = int(math.ceil(source.size[0] / 8.0))

        data = []
        for line in _chunked(list(source.getdata()), source.size[0]):
            row = ''.join(['0' if p else '1' for p in line])
            row = row.ljust(width * 8, '0')
            data.append(row)
        data = GRFData(width, bin=''.join(data))

        return cls(filename, data)
287913
def container_tree(container=None,image_package=None):
    '''
    '''

    guts = get_container_contents(container=container,
                                  image_package=image_package,
                                  split_delim="\n")

    # Make the tree and return it
    tree = make_container_tree(folders = guts["folders.txt"],
                               files = guts['files.txt'])
    return tree
103192
def collect_local(self, path):
        
        for f in os.listdir(path):
            lpath = os.path.join(path, f)
            if not os.path.isfile(lpath):
                continue
            Artifact(self, lpath)
957330
function unpackPNG(w, h, c, str) {
  var canvas = document.createElement("canvas")
  canvas.width = h
  canvas.height = w
  var img = new Image()
  img.src = "data:image/png;base64," + str
  var context = canvas.getContext("2d")
  context.drawImage(img, 0, 0)
  var pixels = context.getImageData(0, 0, h, w)
  return ndarray(pixels.data, [w, h, c], [4, 4*w, 1], 0)
}
442365
def convert_image(from_file, to_file, image_format):
    """"""
    with Image(filename=from_file) as original:
        with original.convert(image_format) as converted:
            converted.save(filename=to_file)
    return to_file
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
569687
def pickledump(theobject, fname):
    """"""
    fhandle = open(fname, 'wb')
    pickle.dump(theobject, fhandle)
930362
function image_local(&$content, $dir='')
	{
	    if(empty($dir)) $dir = UPLOAD_DIR.'/extend/'.date('Ym')."/".date("d");
		if(!file_exists($dir))
		{
			mkdir(WEBPATH.$dir,0777,true);
		}
		$chunklist = array ();
		$chunklist = explode("\n",$content);
		$links = array ();
		$regs = array ();
		$source = array();
		$i = 0;
		while(list ($id, $chunk) = each($chunklist))
		{
			if (strstr(strtolower($chunk),"img") && strstr(strtolower($chunk), "src"))
			{
				while (eregi("(img[^>]*src[[:blank:]]*)=[[:blank:]]*[\'\"]?(([[a-z]{3,5}://(([.a-zA-Z0-9-])+(:[0-9]+)*))*([+:%/?=&;\\\(\),._a-zA-Z0-9-]*))(#[.a-zA-Z0-9-]*)?[\'\" ]?", $chunk, $regs))
				{
					if($regs[2])
					{
						$i++;
						$source[$i] = $regs[2];
					}
					$chunk = str_replace($regs[0], "", $chunk);
				}
			}
		}
		$newImg = array();
		foreach($source as $uri)
		{
			if(!strstr(WEBROOT,$uri) and $uri{0}!='/')
			{
				$filename=substr(time(),6,-1).rand(100000,999999).".jpg";
				copy($uri,WEBPATH.$dir.'/'.$filename);
				$content = str_replace($uri,WEBROOT.$dir."/".$filename,$content);
			}
		}
	}
785489
def write_image_to_disk(self, msg, result, fh):
        """"""
        cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh)
816010
def from_lists(cls, path:PathOrStr, fnames:FilePathList, labels:Collection[str], valid_pct:float=0.2,
                   item_cls:Callable=None, **kwargs):
        ""
        item_cls = ifnone(item_cls, ImageList)
        fname2label = {f:l for (f,l) in zip(fnames, labels)}
        src = (item_cls(fnames, path=path).split_by_rand_pct(valid_pct)
                                .label_from_func(lambda x:fname2label[x]))
        return cls.create_from_ll(src, **kwargs)
446774
def convert(f, output=sys.stdout):
    

    r = f.read(11)
    if r == 'compressed\n':
        png(output, *decompress(f))
    else:
        png(output, *glue(f, r))
1126263
def load_hat(self, path):  # pylint: disable=no-self-use
        
        hat = cv2.imread(path, cv2.IMREAD_UNCHANGED)
        if hat is None:
            raise ValueError('No hat image found at `{}`'.format(path))
        b, g, r, a = cv2.split(hat)
        return cv2.merge((r, g, b, a))
157807
async def crunch(image_data, format, silent=False):
    
    if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or
            ((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))):
      return image_data
    with mkstemp_ctx.mkstemp(suffix=".%s" % (format.name.lower())) as tmp_out_filepath:
      if not silent:
        logging.getLogger("Cover").info("Crunching %s image..." % (format.name.upper()))
      with open(tmp_out_filepath, "wb") as tmp_out_file:
        tmp_out_file.write(image_data)
      size_before = len(image_data)
      if format is CoverImageFormat.PNG:
        cmd = ["optipng", "-quiet", "-o1"]
      elif format is CoverImageFormat.JPEG:
        cmd = ["jpegoptim", "-q", "--strip-all"]
      cmd.append(tmp_out_filepath)
      p = await asyncio.create_subprocess_exec(*cmd,
                                               stdin=asyncio.subprocess.DEVNULL,
                                               stdout=asyncio.subprocess.DEVNULL,
                                               stderr=asyncio.subprocess.DEVNULL)
      await p.wait()
      if p.returncode != 0:
        if not silent:
          logging.getLogger("Cover").warning("Crunching image failed")
        return image_data
      with open(tmp_out_filepath, "rb") as tmp_out_file:
        crunched_image_data = tmp_out_file.read()
      size_after = len(crunched_image_data)
      pct_saved = 100 * (size_before - size_after) / size_before
      if not silent:
        logging.getLogger("Cover").debug("Crunching image saved %.2f%% filesize" % (pct_saved))
    return crunched_image_data
1263617
def local_data(path):
    """"""
    dirs = [os.path.join(path, item) for item in os.listdir(path)]
    names, sizes, files = zip(*[(dir.split('/')[-1], str(get_size(dir)),
                                 '##'.join([file for file in os.listdir(dir)]))
                                for dir in dirs])
    return zip(names, dirs, sizes, files)
540287
def get(img, cache_dir=CACHE_DIR, iterative=False):
    """"""
    if os.path.isfile(img):
        wal_img = img

    elif os.path.isdir(img):
        if iterative:
            wal_img = get_next_image(img)

        else:
            wal_img = get_random_image(img)

    else:
        logging.error("No valid image file found.")
        sys.exit(1)

    wal_img = os.path.abspath(wal_img)

    # Cache the image file path.
    util.save_file(wal_img, os.path.join(cache_dir, "wal"))

    logging.info("Using image \033[1;37m%s\033[0m.", os.path.basename(wal_img))
    return wal_img
405014
def _local_upload(self, filepath, remove=False):
        """"""
        if os.path.isfile(filepath):
            filename = os.path.basename(os.path.abspath(filepath))
            if filename and self.__isValidFilename(filename):
                suffix = self.__getFilenameSuffix(filename)
                try:
                    self.__unpack_tgz(os.path.abspath(filepath)) if self.__isValidTGZ(suffix) else self.__unpack_zip(os.path.abspath(filepath))
                finally:
                    if remove is True:
                        os.remove(filepath)
            else:
                raise InstallError("Invalid Filename")
        else:
            raise InstallError("Invalid Filepath")