Extract information from the image file such as dimension, type, filename,
 and extension. Also keep track of previously seen images to optimise out
 any duplicates.
501401
def get_image_properties(filename)
      # Note the image_id, and previous_images mechanism isn't currently used.
      x_dpi = 96
      y_dpi = 96

      # Open the image file and import the data.
      data = File.binread(filename)
      if data.unpack('x A3')[0] == 'PNG'
        # Test for PNGs.
        type, width, height, x_dpi, y_dpi = process_png(data)
        @image_types[:png] = 1
      elsif data.unpack('n')[0] == 0xFFD8
        # Test for JPEG files.
        type, width, height, x_dpi, y_dpi = process_jpg(data, filename)
        @image_types[:jpeg] = 1
      elsif data.unpack('A2')[0] == 'BM'
        # Test for BMPs.
        type, width, height = process_bmp(data, filename)
        @image_types[:bmp] = 1
      else
        # TODO. Add Image::Size to support other types.
        raise "Unsupported image format for file: #{filename}\n"
      end

      @images << [filename, type]

      [type, width, height, File.basename(filename), x_dpi, y_dpi]
    end
595400
def file_is_image?(file)
      return unless file && file.respond_to?(:url)
      return file.content_type.start_with? "image" if file.content_type.present?
      Mime::Type.lookup_by_extension(File.extname(file.url)[1..-1]).to_s.start_with? "image" if file.url.present?
    end
732633
def _get_imagesave_wildcards(self):
        ''
        default_filetype = self.get_default_filetype()
        filetypes = self.get_supported_filetypes_grouped()
        sorted_filetypes = filetypes.items()
        sorted_filetypes.sort()
        wildcards = []
        extensions = []
        filter_index = 0
        for i, (name, exts) in enumerate(sorted_filetypes):
            ext_list = ';'.join(['*.%s' % ext for ext in exts])
            extensions.append(exts[0])
            wildcard = '%s (%s)|%s' % (name, ext_list, ext_list)
            if default_filetype in exts:
                filter_index = i
            wildcards.append(wildcard)
        wildcards = '|'.join(wildcards)
        return wildcards, extensions, filter_index
666043
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Assign file extension attribute to file object
        self.fileExtension = extension
        self.filename = filename

        self._load_raster_text(path)
        
        if spatial:
            # Get well known binary from the raster file using the MapKit RasterLoader
            wkbRaster = RasterLoader.grassAsciiRasterToWKB(session=session,
                                                           grassRasterPath=path,
                                                           srid=str(spatialReferenceID),
                                                           noData='0')
            self.raster = wkbRaster
887888
def extract_jpeg_thumbnail(self):
        
        thumb_offset = self.tags.get('Thumbnail JPEGInterchangeFormat')
        if thumb_offset:
            self.file.seek(self.offset + thumb_offset.values[0])
            size = self.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]
            self.tags['JPEGThumbnail'] = self.file.read(size)

        # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote
        # since it's not allowed in a uncompressed TIFF IFD
        if 'JPEGThumbnail' not in self.tags:
            thumb_offset = self.tags.get('MakerNote JPEGThumbnail')
            if thumb_offset:
                self.file.seek(self.offset + thumb_offset.values[0])
                self.tags['JPEGThumbnail'] = self.file.read(thumb_offset.field_length)
1349401
def extract_subsec(self):
        '''
        
        '''
        fields = [
            'Image SubSecTimeOriginal',
            'EXIF SubSecTimeOriginal',
            'Image SubSecTimeDigitized',
            'EXIF SubSecTimeDigitized',
            'Image SubSecTime',
            'EXIF SubSecTime'
        ]
        sub_sec, _ = self._extract_alternative_fields(
            fields, default='', field_type=str)
        return sub_sec
1372570
def from_image_to_file(img_path, file_path):
    
    img = Image.open(img_path)
    data = numpy.array(img)
    data = numpy.reshape(data, len(img.getdata()) * 3)
    to_remove = data[len(data) - 1]
    data = numpy.delete(data, xrange(len(data) - to_remove, len(data)))
    data.tofile(file_path)
659785
def extract_images(bs4, lazy_image_attribute=None):
    

    # get images form 'img' tags
    if lazy_image_attribute:

        images = [image[lazy_image_attribute] for image in bs4.select('img') if image.has_attr(lazy_image_attribute)]

    else:

        images = [image['src'] for image in bs4.select('img') if image.has_attr('src')]

    # get images from detected links
    image_links = [link for link in extract_links(bs4) if link.endswith(('.jpg', '.JPG', '.png', '.PNG', '.gif', '.GIF'))]

    # get images from meta content
    image_metas = [meta['content'] for meta in extract_metas(bs4)
                   if 'content' in meta
                   if meta['content'].endswith(('.jpg', '.JPG', '.png', '.PNG', '.gif', '.GIF'))]

    return list(set(images + image_links + image_metas))
1336738
def checkImages(images):
    
    # Init results
    images2 = []

    for im in images:
        if PIL and isinstance(im, PIL.Image.Image):
            # We assume PIL images are allright
            images2.append(im)

        elif np and isinstance(im, np.ndarray):
            # Check and convert dtype
            if im.dtype == np.uint8:
                images2.append(im)  # Ok
            elif im.dtype in [np.float32, np.float64]:
                im = im.copy()
                im[im < 0] = 0
                im[im > 1] = 1
                im *= 255
                images2.append(im.astype(np.uint8))
            else:
                im = im.astype(np.uint8)
                images2.append(im)
            # Check size
            if im.ndim == 2:
                pass  # ok
            elif im.ndim == 3:
                if im.shape[2] not in [3, 4]:
                    raise ValueError('This array can not represent an image.')
            else:
                raise ValueError('This array can not represent an image.')
        else:
            raise ValueError('Invalid image type: ' + str(type(im)))

    # Done
    return images2
377783
def _guess_file_type(self, filename):
        

        # First attempt to guess from the file name.
        namelc = filename.lower()

        if namelc.endswith('.fits') or namelc.endswith('.fit'):
            return 'fits'
        elif namelc.endswith('.json'):
            return 'json'
        elif namelc.endswith('.txt') or namelc.endswith('.ascii'):
            return 'ascii'

        # Otherwise, if the file exists, look at the first character.
        if isfile(filename):
            with open(filename, 'r') as f:
                c = f.read(1)

            if c == 'S':
                return 'fits'
            elif c == '{':
                return 'json'
            elif c.isdigit():
                return 'ascii'

        raise ValueError('Unable to determine format of {0}'.format(filename))
571614
def get_files_information(self):
        
        for k in self.get_files():
            yield k, self.get_files_types()[k], self.get_files_crc32()[k]
317876
def _extract_mnist_images(filename, num_images):
  
  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE * num_images)
    data = np.frombuffer(buf, dtype=np.uint8)
    data = data.reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)
  return data
335730
def load(cls, path_to_file):
        
        import mimetypes
        mimetypes.init()
        mime = mimetypes.guess_type('file://%s' % path_to_file)[0]
        img_type = ImageTypeEnum.lookup_by_mime_type(mime)
        with open(path_to_file, 'rb') as f:
            data = f.read()
        return Image(data, image_type=img_type)
728077
def imdecode(self, s):
        """"""
        def locate():
            """Locate the image file/index if decode fails."""
            if self.seq is not None:
                idx = self.seq[(self.cur % self.num_image) - 1]
            else:
                idx = (self.cur % self.num_image) - 1
            if self.imglist is not None:
                _, fname = self.imglist[idx]
                msg = "filename: {}".format(fname)
            else:
                msg = "index: {}".format(idx)
            return "Broken image " + msg
        try:
            img = imdecode(s)
        except Exception as e:
            raise RuntimeError("{}, {}".format(locate(), e))
        return img
1265497
def getDimensionForImage(filename, maxsize):
    """"""
    try:
        from PIL import Image
    except ImportError:
        return None
    img = Image.open(filename)
    width, height = img.size
    if width > maxsize[0] or height > maxsize[1]:
        img.thumbnail(maxsize)
        out.info("Downscaled display size from %s to %s" % ((width, height), img.size))
    return img.size
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
11422
def extract_exif(self):
        '''
        
        '''
        width, height = self.extract_image_size()
        make, model = self.extract_make(), self.extract_model()
        orientation = self.extract_orientation()
        geo = self.extract_geo()
        capture = self.extract_capture_time()
        direction = self.extract_direction()
        d = {
            'width': width,
            'height': height,
            'orientation': orientation,
            'direction': direction,
            'make': make,
            'model': model,
            'capture_time': capture
        }
        d['gps'] = geo
        return d