Process an image file (expects an open file object).

    This is the function that has to deal with all the arbitrary nasty bits
    of the EXIF standard.
350080
def process_file(f, stop_tag=DEFAULT_STOP_TAG, details=True, strict=False, debug=False):
    

    # by default do not fake an EXIF beginning
    fake_exif = 0

    # determine whether it's a JPEG or TIFF
    data = f.read(12)
    if data[0:4] in [b'II*\x00', b'MM\x00*']:
        # it's a TIFF file
        logger.debug("TIFF format recognized in data[0:4]")
        f.seek(0)
        endian = f.read(1)
        f.read(1)
        offset = 0
    elif data[0:2] == b'\xFF\xD8':
        # it's a JPEG file
        logger.debug("JPEG format recognized data[0:2]=0x%X%X", ord_(data[0]), ord_(data[1]))
        base = 2
        logger.debug("data[2]=0x%X data[3]=0x%X data[6:10]=%s",
                     ord_(data[2]), ord_(data[3]), data[6:10])
        while ord_(data[2]) == 0xFF and data[6:10] in (b'JFIF', b'JFXX', b'OLYM', b'Phot'):
            length = ord_(data[4]) * 256 + ord_(data[5])
            logger.debug(" Length offset is %s", length)
            f.read(length - 8)
            # fake an EXIF beginning of file
            # I don't think this is used. --gd
            data = b'\xFF\x00' + f.read(10)
            fake_exif = 1
            if base > 2:
                logger.debug(" Added to base")
                base = base + length + 4 - 2
            else:
                logger.debug(" Added to zero")
                base = length + 4
            logger.debug(" Set segment base to 0x%X", base)

        # Big ugly patch to deal with APP2 (or other) data coming before APP1
        f.seek(0)
        # in theory, this could be insufficient since 64K is the maximum size--gd
        data = f.read(base + 4000)
        # base = 2
        while 1:
            logger.debug(" Segment base 0x%X", base)
            if data[base:base + 2] == b'\xFF\xE1':
                # APP1
                logger.debug("  APP1 at base 0x%X", base)
                logger.debug("  Length: 0x%X 0x%X", ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug("  Code: %s", data[base + 4:base + 8])
                if data[base + 4:base + 8] == b"Exif":
                    logger.debug("  Decrement base by 2 to get to pre-segment header (for compatibility with later code)")
                    base -= 2
                    break
                increment = increment_base(data, base)
                logger.debug(" Increment base by %s", increment)
                base += increment
            elif data[base:base + 2] == b'\xFF\xE0':
                # APP0
                logger.debug("  APP0 at base 0x%X", base)
                logger.debug("  Length: 0x%X 0x%X", ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug("  Code: %s", data[base + 4:base + 8])
                increment = increment_base(data, base)
                logger.debug(" Increment base by %s", increment)
                base += increment
            elif data[base:base + 2] == b'\xFF\xE2':
                # APP2
                logger.debug("  APP2 at base 0x%X", base)
                logger.debug("  Length: 0x%X 0x%X", ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug(" Code: %s", data[base + 4:base + 8])
                increment = increment_base(data, base)
                logger.debug(" Increment base by %s", increment)
                base += increment
            elif data[base:base + 2] == b'\xFF\xEE':
                # APP14
                logger.debug("  APP14 Adobe segment at base 0x%X", base)
                logger.debug("  Length: 0x%X 0x%X", ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug("  Code: %s", data[base + 4:base + 8])
                increment = increment_base(data, base)
                logger.debug(" Increment base by %s", increment)
                base += increment
                logger.debug("  There is useful EXIF-like data here, but we have no parser for it.")
            elif data[base:base + 2] == b'\xFF\xDB':
                logger.debug("  JPEG image data at base 0x%X No more segments are expected.",
                             base)
                break
            elif data[base:base + 2] == b'\xFF\xD8':
                # APP12
                logger.debug("  FFD8 segment at base 0x%X", base)
                logger.debug("  Got 0x%X 0x%X and %s instead",
                             ord_(data[base]),
                             ord_(data[base + 1]),
                             data[4 + base:10 + base])
                logger.debug("  Length: 0x%X 0x%X", ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug("  Code: %s", data[base + 4:base + 8])
                increment = increment_base(data, base)
                logger.debug("  Increment base by %s", increment)
                base += increment
            elif data[base:base + 2] == b'\xFF\xEC':
                # APP12
                logger.debug("  APP12 XMP (Ducky) or Pictureinfo segment at base 0x%X",
                             base)
                logger.debug("  Got 0x%X and 0x%X instead", ord_(data[base]),
                             ord_(data[base + 1]))
                logger.debug("  Length: 0x%X 0x%X",
                             ord_(data[base + 2]),
                             ord_(data[base + 3]))
                logger.debug("Code: %s", data[base + 4:base + 8])
                increment = increment_base(data, base)
                logger.debug("  Increment base by %s", increment)
                base += increment
                logger.debug(
                    "  There is useful EXIF-like data here (quality, comment, copyright), but we have no parser for it.")
            else:
                try:
                    increment = increment_base(data, base)
                    logger.debug("  Got 0x%X and 0x%X instead",
                                 ord_(data[base]),
                                 ord_(data[base + 1]))
                except IndexError:
                    logger.debug("  Unexpected/unhandled segment type or file content.")
                    return {}
                else:
                    logger.debug("  Increment base by %s", increment)
                    base += increment
        f.seek(base + 12)
        if ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base] == b'Exif':
            # detected EXIF header
            offset = f.tell()
            endian = f.read(1)
            #HACK TEST:  endian = 'M'
        elif ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base + 1] == b'Ducky':
            # detected Ducky header.
            logger.debug("EXIF-like header (normally 0xFF and code): 0x%X and %s",
                         ord_(data[2 + base]), data[6 + base:10 + base + 1])
            offset = f.tell()
            endian = f.read(1)
        elif ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base + 1] == b'Adobe':
            # detected APP14 (Adobe)
            logger.debug("EXIF-like header (normally 0xFF and code): 0x%X and %s",
                         ord_(data[2 + base]), data[6 + base:10 + base + 1])
            offset = f.tell()
            endian = f.read(1)
        else:
            # no EXIF information
            logger.debug("No EXIF header expected data[2+base]==0xFF and data[6+base:10+base]===Exif (or Duck)")
            logger.debug("Did get 0x%X and %s",
                         ord_(data[2 + base]), data[6 + base:10 + base + 1])
            return {}
    else:
        # file format not recognized
        logger.debug("File format not recognized.")
        return {}

    endian = chr(ord_(endian[0]))
    # deal with the EXIF info we found
    logger.debug("Endian format is %s (%s)", endian, {
        'I': 'Intel',
        'M': 'Motorola',
        '\x01': 'Adobe Ducky',
        'd': 'XMP/Adobe unknown'
    }[endian])

    hdr = ExifHeader(f, endian, offset, fake_exif, strict, debug, details)
    ifd_list = hdr.list_ifd()
    thumb_ifd = False
    ctr = 0
    for ifd in ifd_list:
        if ctr == 0:
            ifd_name = 'Image'
        elif ctr == 1:
            ifd_name = 'Thumbnail'
            thumb_ifd = ifd
        else:
            ifd_name = 'IFD %d' % ctr
        logger.debug('IFD %d (%s) at offset %s:', ctr, ifd_name, ifd)
        hdr.dump_ifd(ifd, ifd_name, stop_tag=stop_tag)
        ctr += 1
    # EXIF IFD
    exif_off = hdr.tags.get('Image ExifOffset')
    if exif_off:
        logger.debug('Exif SubIFD at offset %s:', exif_off.values[0])
        hdr.dump_ifd(exif_off.values[0], 'EXIF', stop_tag=stop_tag)

    # deal with MakerNote contained in EXIF IFD
    # (Some apps use MakerNote tags but do not use a format for which we
    # have a description, do not process these).
    if details and 'EXIF MakerNote' in hdr.tags and 'Image Make' in hdr.tags:
        hdr.decode_maker_note()

    # extract thumbnails
    if details and thumb_ifd:
        hdr.extract_tiff_thumbnail(thumb_ifd)
        hdr.extract_jpeg_thumbnail()

    # parse XMP tags (experimental)
    if debug and details:
        xmp_string = b''
        # Easy we already have them
        if 'Image ApplicationNotes' in hdr.tags:
            logger.debug('XMP present in Exif')
            xmp_string = make_string(hdr.tags['Image ApplicationNotes'].values)
        # We need to look in the entire file for the XML
        else:
            logger.debug('XMP not in Exif, searching file for XMP info...')
            xml_started = False
            xml_finished = False
            for line in f:
                open_tag = line.find(b'<x:xmpmeta')
                close_tag = line.find(b'</x:xmpmeta>')

                if open_tag != -1:
                    xml_started = True
                    line = line[open_tag:]
                    logger.debug('XMP found opening tag at line position %s' % open_tag)

                if close_tag != -1:
                    logger.debug('XMP found closing tag at line position %s' % close_tag)
                    line_offset = 0
                    if open_tag != -1:
                        line_offset = open_tag
                    line = line[:(close_tag - line_offset) + 12]
                    xml_finished = True

                if xml_started:
                    xmp_string += line

                if xml_finished:
                    break

            logger.debug('XMP Finished searching for info')
        if xmp_string:
            hdr.parse_xmp(xmp_string)

    return hdr.tags
996489
def from_file(cls, image_file):
        
        if is_string(image_file):
            # treat image_file as a path
            with open(image_file, 'rb') as f:
                blob = f.read()
            filename = os.path.basename(image_file)
        else:
            # assume image_file is a file-like object
            # ---reposition file cursor if it has one---
            if callable(getattr(image_file, 'seek')):
                image_file.seek(0)
            blob = image_file.read()
            filename = None

        return cls.from_blob(blob, filename)
763472
def handle_image_posts(function=None):
    
    @wraps(function, assigned=available_attrs(function))
    def _wrapped_view(request, *args, **kwargs):
        if 'image' in request.META['CONTENT_TYPE']:
            name = default_storage.save(os.path.join('images', 'aloha-uploads', request.META['HTTP_X_FILE_NAME']),
                                        ContentFile(base64.b64decode(request.body.split(",", 1)[1])))
            return HttpResponse(posixpath.join(settings.MEDIA_URL, name), content_type="text/plain")
        else:
            return function(request, *args, **kwargs)
    return _wrapped_view
1372115
function processFile(extension) {
  return (file, callback) => {
    let filePath;
    if (file.meta !== undefined && file.meta.filePath !== undefined) {
      const ext = extension === null
        ? file.meta.filePath.ext
        : extension;
      filePath = path.format(Object.assign({}, file.meta.filePath, { ext }));
    } else {
      filePath = extension === undefined
        ? file.path
        : `${trimExtension(file.path)}${extension}`;
    }

    async.nextTick(callback, null, Object.assign({}, file, { path: filePath }));
  };
}
537140
function (file) {
                var _this = this;
                if (file) {
                    setTimeout(function () {
                        _this.processing.emit(true);
                    }, 5);
                    this.imageLoaded = false;
                    this.originalImage = file;
                    this.ngxOpenCv.cvState.subscribe(function (cvState) {
                        return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (!cvState.ready)
                                            return [3 /*break*/, 2];
                                        // read file to image & canvas
                                        return [4 /*yield*/, this.loadFile(file)];
                                    case 1:
                                        // read file to image & canvas
                                        _a.sent();
                                        this.processing.emit(false);
                                        _a.label = 2;
                                    case 2: return [2 /*return*/];
                                }
                            });
                        });
                    });
                }
            }
1048254
def process(image)
      raise ArgumentError, "process() operates only on ZBar::Image objects" unless image.kind_of?(ZBar::Image)
      image = image.instance_variable_get(:@img)
  
      if ZBar.zbar_process_image(@processor, image) != 0
        raise ArgumentError, "processing failed"
      end
  
      out = []
  
      sym = ZBar.zbar_image_first_symbol(image)
      until sym.null?
        out << Symbol.new(sym)
        sym = ZBar.zbar_symbol_next(sym)
      end
  
      out
    end
333622
protected function process()
    {

        // query whether or not we've to upload the image files
        if ($this->getSubject()->hasCopyImages()) {
            // initialize the image path
            if ($imagePath = $this->getValue(ColumnKeys::IMAGE_PATH)) {
                // upload the file and set the new image path
                $imagePath = $this->getSubject()->uploadFile($imagePath);

                // log a message that the image has been copied
                $this->getSubject()->getSystemLogger()->debug(
                    sprintf('Successfully copied image %s => %s', $imagePath, $imagePath)
                );

                // write the new image path to the target column
                $this->setValue(ColumnKeys::IMAGE_PATH, $imagePath);
            }
        }
    }
1041743
def process_input(self, data, input_prompt, lineno):
        
        decorator, input, rest = data
        image_file = None
        image_directive = None

        is_verbatim = decorator=='@verbatim' or self.is_verbatim
        is_doctest = (decorator is not None and \
                     decorator.startswith('@doctest')) or self.is_doctest
        is_suppress = decorator=='@suppress' or self.is_suppress
        is_okexcept = decorator=='@okexcept' or self.is_okexcept
        is_okwarning = decorator=='@okwarning' or self.is_okwarning
        is_savefig = decorator is not None and \
                     decorator.startswith('@savefig')

        # set the encodings to be used by DecodingStringIO
        # to convert the execution output into unicode if
        # needed. this attrib is set by IpythonDirective.run()
        # based on the specified block options, defaulting to ['ut
        self.cout.set_encodings(self.output_encoding)

        input_lines = input.split('\n')

        if len(input_lines) > 1:
           if input_lines[-1] != "":
               input_lines.append('') # make sure there's a blank line
                                       # so splitter buffer gets reset

        continuation = '   %s:'%''.join(['.']*(len(str(lineno))+2))

        if is_savefig:
            image_file, image_directive = self.process_image(decorator)

        ret = []
        is_semicolon = False

        # Hold the execution count, if requested to do so.
        if is_suppress and self.hold_count:
            store_history = False
        else:
            store_history = True

        # Note: catch_warnings is not thread safe
        with warnings.catch_warnings(record=True) as ws:
            for i, line in enumerate(input_lines):
                if line.endswith(';'):
                    is_semicolon = True

                if i == 0:
                    # process the first input line
                    if is_verbatim:
                        self.process_input_line('')
                        self.IP.execution_count += 1 # increment it anyway
                    else:
                        # only submit the line in non-verbatim mode
                        self.process_input_line(line, store_history=store_history)
                    formatted_line = '%s %s'%(input_prompt, line)
                else:
                    # process a continuation line
                    if not is_verbatim:
                        self.process_input_line(line, store_history=store_history)

                    formatted_line = '%s %s'%(continuation, line)

                if not is_suppress:
                    ret.append(formatted_line)

        if not is_suppress and len(rest.strip()) and is_verbatim:
            # the "rest" is the standard output of the
            # input, which needs to be added in
            # verbatim mode
            ret.append(rest)

        self.cout.seek(0)
        output = self.cout.read()
        if not is_suppress and not is_semicolon:
            ret.append(output)
        elif is_semicolon: # get spacing right
            ret.append('')

        # context information
        filename = self.state.document.current_source
        lineno = self.state.document.current_line

        # output any exceptions raised during execution to stdout
        # unless :okexcept: has been specified.
        if not is_okexcept and "Traceback" in output:
            s =  "\nException in %s at block ending on line %s\n" % (filename, lineno)
            s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
            sys.stdout.write('\n\n>>>' + ('-' * 73))
            sys.stdout.write(s)
            sys.stdout.write(output)
            sys.stdout.write('<<<' + ('-' * 73) + '\n\n')

        # output any warning raised during execution to stdout
        # unless :okwarning: has been specified.
        if not is_okwarning:
            for w in ws:
                s =  "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
                s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
                sys.stdout.write('\n\n>>>' + ('-' * 73))
                sys.stdout.write(s)
                sys.stdout.write('-' * 76 + '\n')
                s=warnings.formatwarning(w.message, w.category,
                                         w.filename, w.lineno, w.line)
                sys.stdout.write(s)
                sys.stdout.write('<<<' + ('-' * 73) + '\n')

        self.cout.truncate(0)
        return (ret, input_lines, output, is_doctest, decorator, image_file,
                    image_directive)
1114010
def resolve_image_exif(self, image_url):
        
        files = self.mets.find_files(url=image_url)
        if files:
            image_filename = self.download_file(files[0]).local_filename
        else:
            image_filename = self.download_url(image_url)

        if image_url not in self.image_cache['exif']:
            self.image_cache['exif'][image_url] = OcrdExif(Image.open(image_filename))
        return self.image_cache['exif'][image_url]
314123
def open_image(fn):
    
    flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLOR
    if not os.path.exists(fn) and not str(fn).startswith("http"):
        raise OSError('No such file or directory: {}'.format(fn))
    elif os.path.isdir(fn) and not str(fn).startswith("http"):
        raise OSError('Is a directory: {}'.format(fn))
    elif isdicom(fn):
        slice = pydicom.read_file(fn)
        if slice.PhotometricInterpretation.startswith('MONOCHROME'):
            # Make a fake RGB image
            im = np.stack([slice.pixel_array]*3,-1)
            return im / ((1 << slice.BitsStored)-1)
        else:
            # No support for RGB yet, as it involves various color spaces.
            # It shouldn't be too difficult to add though, if needed.
            raise OSError('Unsupported DICOM image with PhotometricInterpretation=={}'.format(slice.PhotometricInterpretation))
    else:
        #res = np.array(Image.open(fn), dtype=np.float32)/255
        #if len(res.shape)==2: res = np.repeat(res[...,None],3,2)
        #return res
        try:
            if str(fn).startswith("http"):
                req = urllib.urlopen(str(fn))
                image = np.asarray(bytearray(req.read()), dtype="uint8")
                im = cv2.imdecode(image, flags).astype(np.float32)/255
            else:
                im = cv2.imread(str(fn), flags).astype(np.float32)/255
            if im is None: raise OSError(f'File not recognized by opencv: {fn}')
            return cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
        except Exception as e:
            raise OSError('Error handling image at: {}'.format(fn)) from e
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end
752404
def process(name)
      self.ext = File.extname(name)
      self.basename = name[0..-ext.length - 1].gsub(%r!\.*\z!, "")
    end
165361
def _tiff_from_exif_segment(cls, stream, offset, segment_length):
        
        # wrap full segment in its own stream and feed to Tiff()
        stream.seek(offset+8)
        segment_bytes = stream.read(segment_length-8)
        substream = BytesIO(segment_bytes)
        return Tiff.from_stream(substream)
1367346
def resize(image, width=None, height=None, crop=False):
    
    # First normalize params to determine which file to get
    width, height, crop = _normalize_params(image, width, height, crop)

    try:
        # Check the image file state for clean close
        is_closed = image.closed

        if is_closed:
            image.open()

        # Create the resized file
        # Do resize and crop
        resized_image = _resize(image, width, height, crop)
    finally:
        # Re-close if received a closed file
        if is_closed:
            image.close()

    return ImageFile(resized_image)
1202265
function processImage()
    {
        $destinationImageObject = $this->imageObjectInternal();
        $bbox = $this->textBoundingBox();
        $this->clear();
        $font = $this->font();
        $this->drawText( $font, $this->textColor(), $this->text(), $bbox[6], -$bbox[7], $this->textAngle(),
                         $destinationImageObject );
        return true;
    }
386184
def process(image, size, *args, **kwargs):
        
        from autodetect import smart_crop
        box_width, box_height = AutoCrop.parse_size(image, size)
        scaled_size, rect = smart_crop(box_width, box_height, image.filename)
        return image.resize(scaled_size, Image.ANTIALIAS).crop(tuple(rect))
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)