Return a |Tiff| instance parsed from the Exif APP1 segment of
        *segment_length* at *offset* in *stream*.
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)
118581
def readlocal(path, offset=None, size=-1):
    
    try:
        with open(path, 'rb') as f:
            if offset:
                f.seek(offset)
            buf = f.read(size)
    except IOError as e:
        if e.errno == errno.ENOENT:
            raise FileNotFoundError(e)
        else:
            raise
    return buf
1250873
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize):
    """"""
    exif = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1)
    for name in ('ExifVersion', 'FlashpixVersion'):
        try:
            exif[name] = bytes2str(exif[name])
        except Exception:
            pass
    if 'UserComment' in exif:
        idcode = exif['UserComment'][:8]
        try:
            if idcode == b'ASCII\x00\x00\x00':
                exif['UserComment'] = bytes2str(exif['UserComment'][8:])
            elif idcode == b'UNICODE\x00':
                exif['UserComment'] = exif['UserComment'][8:].decode('utf-16')
        except Exception:
            pass
    return exif
1303146
def split_into_segments(data):
    
    if data[0:2] != b"\xff\xd8":
        raise InvalidImageDataError("Given data isn't JPEG.")

    head = 2
    segments = [b"\xff\xd8"]
    while 1:
        if data[head: head + 2] == b"\xff\xda":
            segments.append(data[head:])
            break
        else:
            length = struct.unpack(">H", data[head + 2: head + 4])[0]
            endPoint = head + length + 2
            seg = data[head: endPoint]
            segments.append(seg)
            head = endPoint

        if (head >= len(data)):
            raise InvalidImageDataError("Wrong JPEG data.")
    return segments
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)
310215
public void extract(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata, int readerOffset, @Nullable Directory parentDirectory)
    {
        ExifTiffHandler exifTiffHandler = new ExifTiffHandler(metadata, parentDirectory);

        try {
            // Read the TIFF-formatted Exif data
            new TiffReader().processTiff(
                reader,
                exifTiffHandler,
                readerOffset
            );
        } catch (TiffProcessingException e) {
            exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
            // TODO what do to with this error state?
            e.printStackTrace(System.err);
        } catch (IOException e) {
            exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
            // TODO what do to with this error state?
            e.printStackTrace(System.err);
        }
    }
195953
function getIfd(app1Start, dirEntries) {
        var offset = app1Start + 20,
            bytes = dirEntries * 12;

        return qq.readBlobToHex(fileOrBlob, offset, bytes);
    }
845999
function getOrientation(arrayBuffer) {
  var dataView = new DataView(arrayBuffer);
  var length = dataView.byteLength;
  var orientation;
  var exifIDCode;
  var tiffOffset;
  var firstIFDOffset;
  var littleEndian;
  var endianness;
  var app1Start;
  var ifdStart;
  var offset;
  var i;
  // Only handle JPEG image (start by 0xFFD8)
  if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {
    offset = 2;
    while (offset < length) {
      if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {
        app1Start = offset;
        break;
      }
      offset++;
    }
  }
  if (app1Start) {
    exifIDCode = app1Start + 4;
    tiffOffset = app1Start + 10;
    if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {
      endianness = dataView.getUint16(tiffOffset);
      littleEndian = endianness === 0x4949;

      if (littleEndian || endianness === 0x4D4D /* bigEndian */) {
        if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {
          firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);

          if (firstIFDOffset >= 0x00000008) {
            ifdStart = tiffOffset + firstIFDOffset;
          }
        }
      }
    }
  }
  if (ifdStart) {
    length = dataView.getUint16(ifdStart, littleEndian);

    for (i = 0; i < length; i++) {
      offset = ifdStart + i * 12 + 2;
      if (dataView.getUint16(offset, littleEndian) === 0x0112 /* Orientation */) {

        // 8 is the offset of the current tag's value
        offset += 8;

        // Get the original orientation value
        orientation = dataView.getUint16(offset, littleEndian);

        // Override the orientation with its default value for Safari (#120)
        // if (IS_SAFARI_OR_UIWEBVIEW) {
        //   dataView.setUint16(offset, 1, littleEndian);
        // }
        break;
      }
    }
  }
  return orientation;
}
802485
def get_flash_region(self, offset, length):
        
        return self._get(GetBytesFlashRequest(offset=offset, length=length))
95282
private static int readTiffHeader(InputStream is, int length, TiffHeader tiffHeader)
      throws IOException {
    if (length <= 8) {
      return 0;
    }

    // read the byte order
    tiffHeader.byteOrder = StreamProcessor.readPackedInt(is, 4, false);
    length -= 4;
    if (tiffHeader.byteOrder != TIFF_BYTE_ORDER_LITTLE_END &&
        tiffHeader.byteOrder != TIFF_BYTE_ORDER_BIG_END) {
      FLog.e(TAG, "Invalid TIFF header");
      return 0;
    }
    tiffHeader.isLittleEndian = (tiffHeader.byteOrder == TIFF_BYTE_ORDER_LITTLE_END);

    // read the offset of the first IFD and check if it is reasonable
    tiffHeader.firstIfdOffset = StreamProcessor.readPackedInt(is, 4, tiffHeader.isLittleEndian);
    length -= 4;
    if (tiffHeader.firstIfdOffset < 8 || tiffHeader.firstIfdOffset - 8 > length) {
      FLog.e(TAG, "Invalid offset");
      return 0;
    }

    return length;
  }
1220737
def get_offset(self):
    
    if not self._is_open:
      raise IOError('Not opened.')

    if self._fsntfs_data_stream:
      return self._fsntfs_data_stream.get_offset()
    return self._fsntfs_file_entry.get_offset()
536934
def _parse_reserved_segment(self, fptr):
        
        offset = fptr.tell() - 2

        read_buffer = fptr.read(2)
        length, = struct.unpack('>H', read_buffer)
        if length > 0:
            data = fptr.read(length - 2)
        else:
            data = None

        segment = Segment(marker_id='0x{0:x}'.format(self._marker_id),
                          offset=offset, length=length, data=data)
        return segment
1048918
def _pfp__parse(self, stream, save_offset=False):
        
        if save_offset:
            self._pfp__offset = stream.tell()

        if self.bitsize is None:
            raw_data = stream.read(self.width)
            data = utils.binary(raw_data)

        else:
            bits = self.bitfield_rw.read_bits(stream, self.bitsize, self.bitfield_padded, self.bitfield_left_right, self.endian)
            width_diff = self.width  - (len(bits)//8) - 1
            bits_diff = 8 - (len(bits) % 8)

            padding = [0] * (width_diff * 8 + bits_diff)

            bits = padding + bits

            data = bitwrap.bits_to_bytes(bits)
            if self.endian == LITTLE_ENDIAN:
                # reverse the data
                data = data[::-1]

        if len(data) < self.width:
            raise errors.PrematureEOF()

        self._pfp__data = data
        self._pfp__value = struct.unpack(
            "{}{}".format(self.endian, self.format),
            data
        )[0]

        return self.width
484274
def read(self, offset, length):
        
        self._file.seek(offset)
        return self._file.read(length)
934396
def _fromfile(self):
        """"""
        self._fd.seek(0)
        try:
            self.byte_order = {b'II': '<', b'MM': '>'}[self._fd.read(2)]
        except KeyError:
            raise ValueError("not a valid TIFF file")
        version = struct.unpack(self.byte_order+'H', self._fd.read(2))[0]
        if version == 43:  # BigTiff
            self.offset_size, zero = struct.unpack(self.byte_order+'HH',
                                                   self._fd.read(4))
            if zero or self.offset_size != 8:
                raise ValueError("not a valid BigTIFF file")
        elif version == 42:
            self.offset_size = 4
        else:
            raise ValueError("not a TIFF file")
        self.pages = []
        while True:
            try:
                page = TIFFpage(self)
                self.pages.append(page)
            except StopIteration:
                break
        if not self.pages:
            raise ValueError("empty TIFF file")
793088
def cropped(self, t0, t1):
        """"""
        return Line(self.point(t0), self.point(t1))
1289830
def read_exif_from_file(filename):
    
    f = open(filename, "rb")
    data = f.read(6)

    if data[0:2] != b"\xff\xd8":
        raise InvalidImageDataError("Given data isn't JPEG.")

    head = data[2:6]
    HEAD_LENGTH = 4
    exif = None
    while 1:
        length = struct.unpack(">H", head[2: 4])[0]

        if head[:2] == b"\xff\xe1":
            segment_data = f.read(length - 2)
            if segment_data[:4] != b'Exif':
                head = f.read(HEAD_LENGTH)
                continue
            exif = head + segment_data
            break
        elif head[0:1] == b"\xff":
            f.read(length - 2)
            head = f.read(HEAD_LENGTH)
        else:
            break

    f.close()
    return exif