Read BlipJPEG record. Holds raw JPEG image data
541624
private function readBlipJPEG()
    {
        // offset: 0; size: 2; recVer and recInstance

        // bit: 4-15; mask: 0xFFF0; recInstance
        $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4;

        $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4);
        $recordData = substr($this->data, $this->pos + 8, $length);

        // move stream pointer to next record
        $this->pos += 8 + $length;

        $pos = 0;

        // offset: 0; size: 16; rgbUid1 (MD4 digest of)
        $rgbUid1 = substr($recordData, 0, 16);
        $pos += 16;

        // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3
        if (in_array($recInstance, array(0x046B, 0x06E3))) {
            $rgbUid2 = substr($recordData, 16, 16);
            $pos += 16;
        }

        // offset: var; size: 1; tag
        $tag = ord($recordData{$pos});
        $pos += 1;

        // offset: var; size: var; the raw image data
        $data = substr($recordData, $pos);

        $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip();
        $blip->setData($data);

        $this->object->setBlip($blip);
    }
833844
def read(self):
        """"""
        stream = BytesIO()
        self.cam.capture(stream, format='png')
        # "Rewind" the stream to the beginning so we can read its content
        stream.seek(0)
        return Image.open(stream)
476369
function readFromSnapshotSub (entityContent, dock, buffer, offset, length, position, cb) {
    var p;
    if ((position !== null) && (position !== undefined)) {
      p = position;
    } else {
      p = dock.position;
    }
    if (cb) {
      payloadCopyUni(entityContent, buffer, offset, p, p + length, function (error, bytesRead, buffer2) {
        if (error) return cb(error);
        dock.position = p + bytesRead;
        cb(null, bytesRead, buffer2);
      });
    } else {
      var bytesRead = payloadCopyUni(entityContent, buffer, offset, p, p + length);
      dock.position = p + bytesRead;
      return bytesRead;
    }
  }
1060140
private function readImData()
    {
        $length = self::getInt2d($this->data, $this->pos + 2);

        // get spliced record data
        $splicedRecordData = $this->getSplicedRecordData();
        $recordData = $splicedRecordData['recordData'];

        // UNDER CONSTRUCTION

        // offset: 0; size: 2; image format
        $cf = self::getInt2d($recordData, 0);

        // offset: 2; size: 2; environment from which the file was written
        $env = self::getInt2d($recordData, 2);

        // offset: 4; size: 4; length of the image data
        $lcb = self::getInt4d($recordData, 4);

        // offset: 8; size: var; image data
        $iData = substr($recordData, 8);

        switch ($cf) {
            case 0x09: // Windows bitmap format
                // BITMAPCOREINFO
                // 1. BITMAPCOREHEADER
                // offset: 0; size: 4; bcSize, Specifies the number of bytes required by the structure
                $bcSize = self::getInt4d($iData, 0);
    //            var_dump($bcSize);

                // offset: 4; size: 2; bcWidth, specifies the width of the bitmap, in pixels
                $bcWidth = self::getInt2d($iData, 4);
    //            var_dump($bcWidth);

                // offset: 6; size: 2; bcHeight, specifies the height of the bitmap, in pixels.
                $bcHeight = self::getInt2d($iData, 6);
    //            var_dump($bcHeight);
                $ih = imagecreatetruecolor($bcWidth, $bcHeight);

                // offset: 8; size: 2; bcPlanes, specifies the number of planes for the target device. This value must be 1

                // offset: 10; size: 2; bcBitCount specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24
                $bcBitCount = self::getInt2d($iData, 10);
    //            var_dump($bcBitCount);

                $rgbString = substr($iData, 12);
                $rgbTriples = array();
                while (strlen($rgbString) > 0) {
                    $rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString);
                    $rgbString = substr($rgbString, 3);
                }
                $x = 0;
                $y = 0;
                foreach ($rgbTriples as $i => $rgbTriple) {
                    $color = imagecolorallocate($ih, $rgbTriple['r'], $rgbTriple['g'], $rgbTriple['b']);
                    imagesetpixel($ih, $x, $bcHeight - 1 - $y, $color);
                    $x = ($x + 1) % $bcWidth;
                    $y = $y + floor(($x + 1) / $bcWidth);
                }
                //imagepng($ih, 'image.png');

                $drawing = new PHPExcel_Worksheet_Drawing();
                $drawing->setPath($filename);
                $drawing->setWorksheet($this->phpSheet);
                break;
            case 0x02: // Windows metafile or Macintosh PICT format
            case 0x0e: // native format
            default:
                break;
        }

        // getSplicedRecordData() takes care of moving current position in data stream
    }
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
1167146
def file_reader(self):
        """"""
        self.update_config()
        path = self.config['path']
        fourcc = self.metadata.get('fourcc')
        xlen, ylen = self.metadata.image_size()
        # set bits per pixel and component dimensions
        if fourcc in ('BGR[24]',):
            bpp = 24
            Y_shape = (ylen, xlen)
        elif fourcc in ('RGB[24]',):
            bpp = 24
            Y_shape = (ylen, xlen, 3)
        elif fourcc in ('IYU2',):
            bpp = 24
            Y_shape = (ylen, xlen, 1)
            UV_shape = (ylen, xlen)
        elif fourcc in ('UYVY', 'UYNV', 'Y422', 'HDYC', 'YVYU', 'YUYV',
                        'YV16', 'YUY2', 'YUNV', 'V422'):
            bpp = 16
            Y_shape = (ylen, xlen, 1)
            UV_shape = (ylen, xlen // 2)
        elif fourcc in ('IYUV', 'I420', 'YV12'):
            bpp = 12
            Y_shape = (ylen, xlen, 1)
            UV_shape = (ylen // 2, xlen // 2)
        elif fourcc in ('YVU9',):
            bpp = 9
            Y_shape = (ylen, xlen, 1)
            UV_shape = (ylen // 4, xlen // 4)
        else:
            self.logger.critical("Can't open %s files", fourcc)
            return
        bytes_per_frame = (xlen * ylen * bpp) // 8
        zlen = os.path.getsize(path) // bytes_per_frame
        if zlen < 1:
            self.logger.critical("Zero length file %s", path)
            return
        # set raw array slice parameters
        if fourcc in ('BGR[24]',):
            Y_slice = ((2, None, 3), (1, None, 3), (0, None, 3))
            UV_slice = None
        elif fourcc in ('RGB[24]',):
            Y_slice = ((0, None, 1),)
            UV_slice = None
        elif fourcc in ('IYU2',):
            Y_slice = ((1, None, 3),)
            UV_slice = ((0, None, 3), (2, None, 3))
        elif fourcc in ('UYVY', 'UYNV', 'Y422', 'HDYC'):
            # packed format, UYVY order
            Y_slice = ((1, None, 2),)
            UV_slice = ((0, None, 4), (2, None, 4))
        elif fourcc in ('YVYU',):
            # packed format, YVYU order
            Y_slice = ((0, None, 2),)
            UV_slice = ((3, None, 4), (1, None, 4))
        elif fourcc in ('YUYV', 'YUY2', 'YUNV', 'V422'):
            # packed format, YUYV order
            Y_slice = ((0, None, 2),)
            UV_slice = ((1, None, 4), (3, None, 4))
        elif fourcc in ('IYUV', 'I420'):
            # planar format, YUV order
            Y_size = xlen * ylen
            UV_size = UV_shape[0] * UV_shape[1]
            Y_slice = ((0,                Y_size,                 1),)
            UV_slice = ((Y_size,           Y_size + UV_size,       1),
                        (Y_size + UV_size, Y_size + (UV_size * 2), 1))
        elif fourcc in ('YV16', 'YV12', 'YVU9'):
            # planar format, YVU order
            Y_size = xlen * ylen
            UV_size = UV_shape[0] * UV_shape[1]
            Y_slice = ((0,                Y_size,                 1),)
            UV_slice = ((Y_size + UV_size, Y_size + (UV_size * 2), 1),
                        (Y_size,           Y_size + UV_size,       1))
        else:
            self.logger.critical("Can't open %s files", fourcc)
            return
        # set frame type
        if fourcc in ('BGR[24]', 'RGB[24]'):
            self.Y_type = 'RGB'
        else:
            self.Y_type = 'Y'
            self.UV_type = 'CbCr'
        file_frame = 0
        direction = 1
        with io.open(path, 'rb', 0) as raw_file:
            while True:
                self.update_config()
                if file_frame >= zlen:
                    if self.config['looping'] == 'off':
                        break
                    elif self.config['looping'] == 'repeat':
                        file_frame = 0
                        raw_file.seek(0)
                    else:
                        file_frame = zlen - 2
                        direction = -1
                elif file_frame < 0:
                    file_frame = 1
                    direction = 1
                if direction != 1:
                    raw_file.seek((direction - 1) * bytes_per_frame, io.SEEK_CUR)
                file_frame += direction
                raw_data = raw_file.read(bytes_per_frame)
                # convert to numpy arrays
                raw_array = numpy.frombuffer(raw_data, numpy.uint8)
                Y_data = []
                for start, end, step in Y_slice:
                    raw_data = raw_array[start:end:step]
                    Y_data.append(raw_data.reshape(Y_shape))
                if len(Y_data) > 1:
                    Y_data = numpy.dstack(Y_data)
                else:
                    Y_data = Y_data[0]
                if UV_slice:
                    UV_data = []
                    for start, end, step in UV_slice:
                        raw_data = raw_array[start:end:step]
                        UV_data.append(raw_data.reshape(UV_shape))
                    UV_data = numpy.dstack(UV_data)
                    # remove offset
                    UV_data = UV_data.astype(pt_float) - pt_float(128.0)
                else:
                    UV_data = None
                yield Y_data, UV_data
803242
private void readChunkIfNeeded() {
        if (workBufferSize > workBufferPosition) {
            return;
        }
        if (workBuffer == null) {
            workBuffer = bitmapProvider.obtainByteArray(WORK_BUFFER_SIZE);
        }
        workBufferPosition = 0;
        workBufferSize = Math.min(rawData.remaining(), WORK_BUFFER_SIZE);
        rawData.get(workBuffer, 0, workBufferSize);
    }
1119645
def _read_image_data( mhd_file):
    
    tempdir = get_tempdir()
    
    # Load description from mhd file
    fname = tempdir + '/' + mhd_file
    des = open(fname, 'r').read()
    
    # Get data filename and load raw data
    match = re.findall('ElementDataFile = (.+?)\n', des)
    fname = tempdir + '/' + match[0]
    data = open(fname, 'rb').read()
    
    # Determine dtype
    match = re.findall('ElementType = (.+?)\n', des)
    dtype_itk = match[0].upper().strip()
    dtype = DTYPE_ITK2NP.get(dtype_itk, None)
    if dtype is None:
        raise RuntimeError('Unknown ElementType: ' + dtype_itk)
    
    # Create numpy array
    a = np.frombuffer(data, dtype=dtype)
    
    # Determine shape, sampling and origin of the data
    match = re.findall('DimSize = (.+?)\n', des)
    shape = [int(i) for i in match[0].split(' ')]
    #
    match = re.findall('ElementSpacing = (.+?)\n', des)
    sampling = [float(i) for i in match[0].split(' ')]
    #
    match = re.findall('Offset = (.+?)\n', des)
    origin = [float(i) for i in match[0].split(' ')]
    
    # Reverse shape stuff to make z-y-x order
    shape = [s for s in reversed(shape)]
    sampling = [s for s in reversed(sampling)]
    origin = [s for s in reversed(origin)]
    
    # Take vectors/colours into account
    N = np.prod(shape)
    if N != a.size:
        extraDim = int( a.size / N )
        shape = tuple(shape) + (extraDim,)
        sampling = tuple(sampling) + (1.0,)
        origin = tuple(origin) + (0,)
    
    # Check shape
    N = np.prod(shape)
    if N != a.size:
        raise RuntimeError('Cannot apply shape to data.')
    else:
        a.shape = shape
        a = Image(a)
        a.sampling = sampling
        a.origin = origin
    return a
1116091
function parse_ImData(blob, length, opts) {
	var tgt = blob.l + length;
	var cf = blob.read_shift(2);
	var env = blob.read_shift(2);
	var lcb = blob.read_shift(4);
	var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
	blob.l += lcb;
	return o;
}
1268787
def read(self):
        
        self.reset()
        for dic in self.datamodel.camera_collection.get(): # TODO: search directly for RTSPCameraRow
            if (self.verbose): print(self.pre, "read : dic", dic)
            
            if (dic["classname"] == DataModel.RTSPCameraRow.__name__):
                affinity = -1
                if self.cpu_scheme:
                    affinity = self.cpu_scheme.getAV()
                
                dic.pop("classname")
                device = DataModel.RTSPCameraDevice(**dic) # a neat object with useful methods
                
                print("FilterChainGroup : read : slot    =", device.getLiveMainSlot())
                print("FilterChainGroup : read : address =", device.getMainAddress())
                print("FilterChainGroup : read : _id     =", device._id)
                
                # chain = ManagedFilterchain( # decoding and branching the stream happens here
                # chain = ManagedFilterchain2( # decoding and branching the stream happens here
                chain = LiveManagedFilterchain( # decoding and branching the stream happens here
                    livethread  = self.livethread,
                    openglthreads
                                = self.gpu_handler.openglthreads,
                    address     = device.getMainAddress(),
                    slot        = device.getLiveMainSlot(),
                    _id         = device._id,
                    affinity    = affinity,
                    msreconnect = 10000,
                    # verbose     = True,
                    verbose     =False,
                    
                    shmem_image_dimensions = constant.shmem_image_dimensions,
                    shmem_n_buffer = constant.shmem_n_buffer,
                    shmem_image_interval = constant.shmem_image_interval
                )
                self.chains.append(chain) # important .. otherwise chain will go out of context and get garbage collected
                
            elif (dic["classname"] == DataModel.USBCameraRow.__name__):
                affinity = -1
                if self.cpu_scheme:
                    affinity = self.cpu_scheme.getAV()
                
                dic.pop("classname")
                device = DataModel.USBCameraDevice(**dic) # a neat object with useful methods
                
                print("FilterChainGroup : read : slot    =", device.getLiveMainSlot())
                print("FilterChainGroup : read : address =", device.getMainAddress())
                print("FilterChainGroup : read : _id     =", device._id)
                
                chain = USBManagedFilterchain( # decoding and branching the stream happens here
                    usbthread   = self.usbthread,
                    openglthreads
                                = self.gpu_handler.openglthreads,
                    address     = device.getMainAddress(),
                    slot        = device.getLiveMainSlot(),
                    _id         = device._id,
                    affinity    = affinity,
                    msreconnect = 10000,
                    # verbose     = True,
                    verbose     =False,
                    
                    shmem_image_dimensions = constant.shmem_image_dimensions,
                    shmem_n_buffer = constant.shmem_n_buffer,
                    shmem_image_interval = constant.shmem_image_interval
                )
                self.chains.append(chain)
575171
function readBlobAsDataURL(blob, path) {
                    var reader = new FileReader();
                    reader.onloadend = function(loadedEvent) {
                        var dataURL = loadedEvent.target.result;
                        var blobtype = 'Blob';
                        if (blob instanceof File) {
                            //blobtype = 'File';
                        }
                        updateEncodedBlob(dataURL, path, blobtype);
                    };
                    reader.readAsDataURL(blob);
                }
1322668
async def dump_blob(elem, elem_type=None):
    
    elem_is_blob = isinstance(elem, x.BlobType)
    data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_blob else elem
    if data is None or len(data) == 0:
        return b''
    if isinstance(data, (bytes, bytearray, list)):
        return base64.b16encode(bytes(data))
    else:
        raise ValueError('Unknown blob type')
291747
function handleImageData(handler, xref, res, image) {
    if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
      // For natively supported jpegs send them to the main thread for decoding.
      var dict = image.dict;
      var colorSpace = dict.get('ColorSpace', 'CS');
      colorSpace = ColorSpace.parse(colorSpace, xref, res);
      var numComps = colorSpace.numComps;
      var decodePromise = handler.sendWithPromise('JpegDecode',
                                                  [image.getIR(), numComps]);
      return decodePromise.then(function (message) {
        var data = message.data;
        return new Stream(data, 0, data.length, image.dict);
      });
    } else {
      return Promise.resolve(image);
    }
  }
1038116
def retrieve_blob(self, key, encoding=None):
        '''  '''
        blob_key = self.__retrieve(key)
        if blob_key is None:
            return None
        if not blob_key:
            raise Exception("Invalid blob_key")
        elif blob_key == JiCache.INTERNAL_BLOB:
            blob_data = self.__retrieve_internal_blob(key)
            return blob_data if not encoding else blob_data.decode(encoding)
        else:
            getLogger().debug("Key[{key}] -> [{blob_key}]".format(key=key, blob_key=blob_key))
            blob_file = os.path.join(self.blob_location, blob_key)
            return FileHelper.read(blob_file)
1089625
def get_data(self, ftype='normal'):
        
        camfile_p = ffi.new("CameraFile**")
        lib.gp_file_new(camfile_p)
        lib.gp_camera_file_get(
            self._cam._cam, self.directory.path.encode(), self.name.encode(),
            backend.FILE_TYPES[ftype], camfile_p[0], self._cam._ctx)
        data_p = ffi.new("char**")
        length_p = ffi.new("unsigned long*")
        lib.gp_file_get_data_and_size(camfile_p[0], data_p, length_p)
        byt = bytes(ffi.buffer(data_p[0], length_p[0]))
        # gphoto2 camera files MUST be freed.
        lib.gp_file_free(camfile_p[0])
        # just to be safe.
        del data_p, length_p, camfile_p
        return byt
918846
def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'blipFill'
          @path_to_image = DocxBlip.new(parent: self).parse(node_child)
        when 'spPr'
          @properties = DocxShapeProperties.new(parent: self).parse(node_child)
        when 'nvPicPr'
          @non_visual_properties = NonVisualShapeProperties.new(parent: self).parse(node_child)
        end
      end
      self
    end
1077154
def get_qpimage(self, idx):
        """"""
        # raw data
        qpi = self.get_qpimage_raw(idx)
        if "identifier" not in qpi:
            msg = "`get_qpimage_raw` does not set 'identifier' " \
                  + "in class '{}'!".format(self.__class__)
            raise KeyError(msg)
        # bg data
        if self._bgdata:
            if len(self._bgdata) == 1:
                # One background for all
                bgidx = 0
            else:
                bgidx = idx

            if isinstance(self._bgdata, SeriesData):
                # `get_qpimage` does take `idx`
                bg = self._bgdata.get_qpimage_raw(bgidx)
            else:
                # `self._bgdata` is a QPImage
                bg = self._bgdata[bgidx]
            qpi.set_bg_data(bg_data=bg)
        return qpi