Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8bc935618 | ||
|
|
150ff8303b | ||
|
|
e44b98ddf9 | ||
|
|
4df26011d9 | ||
|
|
4dc7c2a986 | ||
|
|
b7c4f668ae | ||
|
|
9fe9b2e0a0 | ||
|
|
b7e8f210d1 | ||
|
|
371a9b53c3 | ||
|
|
d0e4f37a28 | ||
|
|
46c7efd836 | ||
|
|
65832e01bd | ||
|
|
b9590e0842 | ||
|
|
521b58dc07 | ||
|
|
e70121efbb | ||
|
|
a6fb855121 | ||
|
|
a874b9c3a5 | ||
|
|
d4ce174236 | ||
|
|
a43aa1fbc7 | ||
|
|
69c34ac33c | ||
|
|
00e0eb9006 | ||
|
|
ebd0e266f7 | ||
|
|
9b94e9de88 | ||
|
|
47dfa0aa3e | ||
|
|
1eb9c4fab7 | ||
|
|
201b95f749 | ||
|
|
7641dcbd3f | ||
|
|
60c6e0cd90 | ||
|
|
65a1c553af | ||
|
|
fddc048849 | ||
|
|
68f2182918 | ||
|
|
b2a7e35c85 | ||
|
|
91fe529859 | ||
|
|
5ca2730416 | ||
|
|
8fcacc829f | ||
|
|
59d0b7389d | ||
|
|
0ac444b63f | ||
|
|
ce1ee6776f | ||
|
|
29a020e5ec | ||
|
|
9021985477 | ||
|
|
d4c958f915 | ||
|
|
dc04282290 | ||
|
|
4cfed1c7b1 | ||
|
|
745ed62808 | ||
|
|
6fe9b78509 | ||
|
|
f5754159cb | ||
|
|
53d0256585 | ||
|
|
09aa28d699 | ||
|
|
d086e289dd | ||
|
|
2cba04dfe7 | ||
|
|
3de87a7001 | ||
|
|
4900c82871 | ||
|
|
8a8e3ed753 | ||
|
|
cd2f4f6462 | ||
|
|
aa13e31894 | ||
|
|
6c211b9179 | ||
|
|
332ab1dc4d | ||
|
|
ec98e32a3b | ||
|
|
7ec2b75c70 | ||
|
|
9788085786 |
No files matched your search
+31
@@ -1,3 +1,34 @@
|
||||
# Version 0.7.0
|
||||
|
||||
New features:
|
||||
* Support for encoding BigTiff ([#122](https://github.com/image-rs/image-tiff/pull/122))
|
||||
* _Breaking:_ Encoder types now have a generic parameter to differentiate BigTiff and standard Tiff encoding. Defaults to standard Tiff.
|
||||
* Basic tile decoding ([#125](https://github.com/image-rs/image-tiff/pull/125))
|
||||
* _Breaking:_ There is a new `TiffError::UsageError` variant.
|
||||
* Support for datatypes `Int8` and `Int16` ([#114](https://github.com/image-rs/image-tiff/pull/114))
|
||||
* _Breaking:_ `DecodingResult` and `DecodingBuffer` have the two new variants `I8` and `I16`.
|
||||
* Support for `i32` arrays ([#118](https://github.com/image-rs/image-tiff/pull/118/files))
|
||||
* _Breaking:_ `DecodingResult` and `DecodingBuffer` have a new `I32` variant.
|
||||
* Support for `Ifd` and `IfdBig` tag types and `I64` data type ([#119](https://github.com/image-rs/image-tiff/pull/119))
|
||||
* _Breaking:_ `DecodingResult` and `DecodingBuffer` have a new `I64` variant.
|
||||
* Add `SMinSampleValue` and `SMaxSampleValue` ([#123](https://github.com/image-rs/image-tiff/pull/123))
|
||||
|
||||
Changes:
|
||||
* Improve deflate support ([#132](https://github.com/image-rs/image-tiff/pull/132))
|
||||
* Switch to streaming decompression via `flate2`. Aside from performance improvements and lower RAM consumption, this fixes a bug where `max_uncompressed_length` was precalculated for a single tile but then used as a hard limit on the whole data, failing to decompress any tiled images.
|
||||
* Add support for new `Deflate` tag in addition to `OldDeflate`.
|
||||
* _Breaking:_ Remove `InflateError`, which is no longer needed with `flate2` ([#134](https://github.com/image-rs/image-tiff/pull/134))
|
||||
* _Breaking:_ Support for `MinIsWhite` is restricted to unsigned and floating
|
||||
point values. This is expected to be be re-added once some contradictory
|
||||
interpretation regarding semantics for signed values is resolved.
|
||||
|
||||
Fixes:
|
||||
* Validate that ASCII tags are valid ASCII and end with a null byte ([#121](https://github.com/image-rs/image-tiff/pull/121))
|
||||
|
||||
Internal:
|
||||
* Simplify decompression logic ([#126](https://github.com/image-rs/image-tiff/pull/126))
|
||||
* Simplify `expand_strip` ([#128](https://github.com/image-rs/image-tiff/pull/128))
|
||||
|
||||
# Version 0.6.1
|
||||
|
||||
New features:
|
||||
|
||||
+2
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tiff"
|
||||
version = "0.6.1"
|
||||
version = "0.7.0"
|
||||
authors = [
|
||||
"ccgn",
|
||||
"bvssvni <bvssvni@gmail.com>",
|
||||
@@ -20,10 +20,7 @@ edition = "2018"
|
||||
[dependencies]
|
||||
weezl = "0.1.0"
|
||||
jpeg = { package = "jpeg-decoder", version = "0.1.17", default-features = false }
|
||||
|
||||
[dependencies.miniz_oxide]
|
||||
version = "0.4.1"
|
||||
features = ["no_extern_crate_alloc"]
|
||||
flate2 = "1.0.20"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = "0.3.1"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# image-tiff
|
||||
[](https://travis-ci.org/image-rs/image-tiff)
|
||||
[](https://github.com/image-rs/image-tiff/actions)
|
||||
[](https://docs.rs/tiff)
|
||||
[](https://crates.io/crates/tiff)
|
||||
|
||||
|
||||
+4
-3
@@ -23,11 +23,12 @@ macro_rules! integral_slice_as_bytes{($int:ty, $const:ident $(,$mut:ident)*) =>
|
||||
})*
|
||||
}}
|
||||
|
||||
integral_slice_as_bytes!(i8, i8_as_ne_bytes);
|
||||
integral_slice_as_bytes!(i8, i8_as_ne_bytes, i8_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(u16, u16_as_ne_bytes, u16_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(i16, i16_as_ne_bytes);
|
||||
integral_slice_as_bytes!(i16, i16_as_ne_bytes, i16_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(u32, u32_as_ne_bytes, u32_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(i32, i32_as_ne_bytes);
|
||||
integral_slice_as_bytes!(i32, i32_as_ne_bytes, i32_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(u64, u64_as_ne_bytes, u64_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(i64, i64_as_ne_bytes, i64_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(f32, f32_as_ne_bytes, f32_as_ne_mut_bytes);
|
||||
integral_slice_as_bytes!(f64, f64_as_ne_bytes, f64_as_ne_mut_bytes);
|
||||
+65
-9
@@ -4,14 +4,15 @@ use std::collections::HashMap;
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::io::{self, Read, Seek};
|
||||
use std::mem;
|
||||
use std::str;
|
||||
|
||||
use super::stream::{ByteOrder, EndianReader, SmartReader};
|
||||
use crate::tags::{Tag, Type};
|
||||
use crate::{TiffError, TiffFormatError, TiffResult};
|
||||
|
||||
use self::Value::{
|
||||
Ascii, Byte, Double, Float, List, Rational, RationalBig, SRational, SRationalBig, Short,
|
||||
Signed, SignedBig, Unsigned, UnsignedBig,
|
||||
Ascii, Byte, Double, Float, Ifd, IfdBig, List, Rational, RationalBig, SRational, SRationalBig,
|
||||
Short, Signed, SignedBig, Unsigned, UnsignedBig,
|
||||
};
|
||||
|
||||
#[allow(unused_qualifications)]
|
||||
@@ -31,6 +32,8 @@ pub enum Value {
|
||||
SRational(i32, i32),
|
||||
SRationalBig(i64, i64),
|
||||
Ascii(String),
|
||||
Ifd(u32),
|
||||
IfdBig(u64),
|
||||
#[doc(hidden)] // Do not match against this.
|
||||
__NonExhaustive,
|
||||
}
|
||||
@@ -59,6 +62,8 @@ impl Value {
|
||||
Short(val) => Ok(val.into()),
|
||||
Unsigned(val) => Ok(val),
|
||||
UnsignedBig(val) => Ok(u32::try_from(val)?),
|
||||
Ifd(val) => Ok(val),
|
||||
IfdBig(val) => Ok(u32::try_from(val)?),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::UnsignedIntegerExpected(val),
|
||||
)),
|
||||
@@ -80,6 +85,8 @@ impl Value {
|
||||
Short(val) => Ok(val.into()),
|
||||
Unsigned(val) => Ok(val.into()),
|
||||
UnsignedBig(val) => Ok(val),
|
||||
Ifd(val) => Ok(val.into()),
|
||||
IfdBig(val) => Ok(val),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::UnsignedIntegerExpected(val),
|
||||
)),
|
||||
@@ -138,6 +145,8 @@ impl Value {
|
||||
RationalBig(numerator, denominator) => {
|
||||
Ok(vec![u32::try_from(numerator)?, u32::try_from(denominator)?])
|
||||
}
|
||||
Ifd(val) => Ok(vec![val]),
|
||||
IfdBig(val) => Ok(vec![u32::try_from(val)?]),
|
||||
Ascii(val) => Ok(val.chars().map(u32::from).collect()),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::UnsignedIntegerExpected(val),
|
||||
@@ -254,6 +263,8 @@ impl Value {
|
||||
UnsignedBig(val) => Ok(vec![val]),
|
||||
Rational(numerator, denominator) => Ok(vec![numerator.into(), denominator.into()]),
|
||||
RationalBig(numerator, denominator) => Ok(vec![numerator, denominator]),
|
||||
Ifd(val) => Ok(vec![val.into()]),
|
||||
IfdBig(val) => Ok(vec![val]),
|
||||
Ascii(val) => Ok(val.chars().map(u32::from).map(u64::from).collect()),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::UnsignedIntegerExpected(val),
|
||||
@@ -342,8 +353,13 @@ impl Entry {
|
||||
* match self.type_ {
|
||||
Type::BYTE | Type::SBYTE | Type::ASCII | Type::UNDEFINED => 1,
|
||||
Type::SHORT | Type::SSHORT => 2,
|
||||
Type::LONG | Type::SLONG | Type::FLOAT => 4,
|
||||
Type::LONG8 | Type::DOUBLE | Type::RATIONAL | Type::SRATIONAL => 8,
|
||||
Type::LONG | Type::SLONG | Type::FLOAT | Type::IFD => 4,
|
||||
Type::LONG8
|
||||
| Type::SLONG8
|
||||
| Type::DOUBLE
|
||||
| Type::RATIONAL
|
||||
| Type::SRATIONAL
|
||||
| Type::IFD8 => 8,
|
||||
Type::__NonExhaustive => unreachable!(),
|
||||
};
|
||||
|
||||
@@ -353,6 +369,7 @@ impl Entry {
|
||||
if decoder.bigtiff && value_bytes > 4 && value_bytes <= 8 {
|
||||
return Ok(match self.type_ {
|
||||
Type::LONG8 => UnsignedBig(self.r(bo).read_u64()?),
|
||||
Type::SLONG8 => SignedBig(self.r(bo).read_i64()?),
|
||||
Type::DOUBLE => Double(self.r(bo).read_f64()?),
|
||||
Type::RATIONAL => {
|
||||
let mut r = self.r(bo);
|
||||
@@ -362,6 +379,7 @@ impl Entry {
|
||||
let mut r = self.r(bo);
|
||||
SRational(r.read_i32()?, r.read_i32()?)
|
||||
}
|
||||
Type::IFD8 => IfdBig(self.r(bo).read_u64()?),
|
||||
Type::BYTE
|
||||
| Type::SBYTE
|
||||
| Type::ASCII
|
||||
@@ -370,7 +388,8 @@ impl Entry {
|
||||
| Type::SSHORT
|
||||
| Type::LONG
|
||||
| Type::SLONG
|
||||
| Type::FLOAT => unreachable!(),
|
||||
| Type::FLOAT
|
||||
| Type::IFD => unreachable!(),
|
||||
Type::__NonExhaustive => unreachable!(),
|
||||
});
|
||||
}
|
||||
@@ -396,6 +415,10 @@ impl Entry {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
UnsignedBig(decoder.read_long8()?)
|
||||
}
|
||||
Type::SLONG8 => {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
SignedBig(decoder.read_slong8()?)
|
||||
}
|
||||
Type::DOUBLE => {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
Double(decoder.read_double()?)
|
||||
@@ -408,6 +431,11 @@ impl Entry {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
SRational(decoder.read_slong()?, decoder.read_slong()?)
|
||||
}
|
||||
Type::IFD => Ifd(self.r(bo).read_u32()?),
|
||||
Type::IFD8 => {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
IfdBig(decoder.read_long8()?)
|
||||
}
|
||||
Type::__NonExhaustive => unreachable!(),
|
||||
});
|
||||
}
|
||||
@@ -420,9 +448,13 @@ impl Entry {
|
||||
Type::ASCII => {
|
||||
let mut buf = vec![0; self.count as usize];
|
||||
self.r(bo).read_exact(&mut buf)?;
|
||||
let v = String::from_utf8(buf)?;
|
||||
let v = v.trim_matches(char::from(0));
|
||||
return Ok(Ascii(v.into()));
|
||||
if buf.is_ascii() && buf.ends_with(&[0]) {
|
||||
let v = str::from_utf8(&buf)?;
|
||||
let v = v.trim_matches(char::from(0));
|
||||
return Ok(Ascii(v.into()));
|
||||
} else {
|
||||
return Err(TiffError::FormatError(TiffFormatError::InvalidTag));
|
||||
}
|
||||
}
|
||||
Type::UNDEFINED => {
|
||||
return Ok(List(
|
||||
@@ -472,7 +504,22 @@ impl Entry {
|
||||
}
|
||||
return Ok(List(v));
|
||||
}
|
||||
Type::LONG8 | Type::RATIONAL | Type::SRATIONAL | Type::DOUBLE => unreachable!(),
|
||||
Type::IFD => {
|
||||
let mut r = self.r(bo);
|
||||
let mut v = Vec::new();
|
||||
for _ in 0..self.count {
|
||||
v.push(Ifd(r.read_u32()?));
|
||||
}
|
||||
return Ok(List(v));
|
||||
}
|
||||
Type::LONG8
|
||||
| Type::SLONG8
|
||||
| Type::RATIONAL
|
||||
| Type::SRATIONAL
|
||||
| Type::DOUBLE
|
||||
| Type::IFD8 => {
|
||||
unreachable!()
|
||||
}
|
||||
Type::__NonExhaustive => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -514,6 +561,15 @@ impl Entry {
|
||||
Type::LONG8 => self.decode_offset(self.count, bo, limits, decoder, |decoder| {
|
||||
Ok(UnsignedBig(decoder.read_long8()?))
|
||||
}),
|
||||
Type::SLONG8 => self.decode_offset(self.count, bo, limits, decoder, |decoder| {
|
||||
Ok(SignedBig(decoder.read_slong8()?))
|
||||
}),
|
||||
Type::IFD => self.decode_offset(self.count, bo, limits, decoder, |decoder| {
|
||||
Ok(Ifd(decoder.read_long()?))
|
||||
}),
|
||||
Type::IFD8 => self.decode_offset(self.count, bo, limits, decoder, |decoder| {
|
||||
Ok(IfdBig(decoder.read_long8()?))
|
||||
}),
|
||||
Type::UNDEFINED => self.decode_offset(self.count, bo, limits, decoder, |decoder| {
|
||||
Ok(Byte(u8::from(decoder.read_byte()?)))
|
||||
}),
|
||||
|
||||
+676
-173
File diff suppressed because it is too large.
Load diff
+53
-213
@@ -1,8 +1,5 @@
|
||||
//! All IO functionality needed for TIFF decoding
|
||||
|
||||
use crate::bytecast;
|
||||
use crate::error::{TiffError, TiffResult};
|
||||
use miniz_oxide::inflate;
|
||||
use std::io::{self, Read, Seek};
|
||||
|
||||
/// Byte order of the TIFF file.
|
||||
@@ -30,22 +27,15 @@ pub trait EndianReader: Read {
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an i8
|
||||
#[inline(always)]
|
||||
fn read_u16_into(&mut self, buffer: &mut [u16]) -> Result<(), io::Error> {
|
||||
self.read_exact(bytecast::u16_as_ne_mut_bytes(buffer))?;
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
for n in buffer {
|
||||
*n = u16::from_le(*n);
|
||||
}
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
for n in buffer {
|
||||
*n = u16::from_be(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
fn read_i8(&mut self) -> Result<i8, io::Error> {
|
||||
let mut n = [0u8; 1];
|
||||
self.read_exact(&mut n)?;
|
||||
Ok(match self.byte_order() {
|
||||
ByteOrder::LittleEndian => i8::from_le_bytes(n),
|
||||
ByteOrder::BigEndian => i8::from_be_bytes(n),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an i16
|
||||
@@ -70,24 +60,6 @@ pub trait EndianReader: Read {
|
||||
})
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_u32_into(&mut self, buffer: &mut [u32]) -> Result<(), io::Error> {
|
||||
self.read_exact(bytecast::u32_as_ne_mut_bytes(buffer))?;
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
for n in buffer {
|
||||
*n = u32::from_le(*n);
|
||||
}
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
for n in buffer {
|
||||
*n = u32::from_be(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads an i32
|
||||
#[inline(always)]
|
||||
fn read_i32(&mut self) -> Result<i32, io::Error> {
|
||||
@@ -110,22 +82,15 @@ pub trait EndianReader: Read {
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an i64
|
||||
#[inline(always)]
|
||||
fn read_u64_into(&mut self, buffer: &mut [u64]) -> Result<(), io::Error> {
|
||||
self.read_exact(bytecast::u64_as_ne_mut_bytes(buffer))?;
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
for n in buffer {
|
||||
*n = u64::from_le(*n);
|
||||
}
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
for n in buffer {
|
||||
*n = u64::from_be(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
fn read_i64(&mut self) -> Result<i64, io::Error> {
|
||||
let mut n = [0u8; 8];
|
||||
self.read_exact(&mut n)?;
|
||||
Ok(match self.byte_order() {
|
||||
ByteOrder::LittleEndian => i64::from_le_bytes(n),
|
||||
ByteOrder::BigEndian => i64::from_be_bytes(n),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an f32
|
||||
@@ -139,24 +104,6 @@ pub trait EndianReader: Read {
|
||||
}))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_f32_into(&mut self, buffer: &mut [f32]) -> Result<(), io::Error> {
|
||||
self.read_exact(bytecast::f32_as_ne_mut_bytes(buffer))?;
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
for n in buffer {
|
||||
*n = f32::from_bits(u32::from_le(n.to_bits()));
|
||||
}
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
for n in buffer {
|
||||
*n = f32::from_bits(u32::from_be(n.to_bits()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads an f64
|
||||
#[inline(always)]
|
||||
fn read_f64(&mut self) -> Result<f64, io::Error> {
|
||||
@@ -167,24 +114,6 @@ pub trait EndianReader: Read {
|
||||
ByteOrder::BigEndian => u64::from_be_bytes(n),
|
||||
}))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_f64_into(&mut self, buffer: &mut [f64]) -> Result<(), io::Error> {
|
||||
self.read_exact(bytecast::f64_as_ne_mut_bytes(buffer))?;
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
for n in buffer {
|
||||
*n = f64::from_bits(u64::from_le(n.to_bits()));
|
||||
}
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
for n in buffer {
|
||||
*n = f64::from_bits(u64::from_be(n.to_bits()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
@@ -195,51 +124,7 @@ pub trait EndianReader: Read {
|
||||
/// ## Deflate Reader
|
||||
///
|
||||
|
||||
/// Reader that decompresses DEFLATE streams
|
||||
pub struct DeflateReader {
|
||||
buffer: io::Cursor<Vec<u8>>,
|
||||
byte_order: ByteOrder,
|
||||
}
|
||||
|
||||
impl DeflateReader {
|
||||
pub fn new<R: Read + Seek>(
|
||||
reader: &mut SmartReader<R>,
|
||||
max_uncompressed_length: usize,
|
||||
) -> TiffResult<(usize, Self)> {
|
||||
let byte_order = reader.byte_order;
|
||||
let mut compressed = Vec::new();
|
||||
reader.read_to_end(&mut compressed)?;
|
||||
|
||||
// TODO: Implement streaming compression, and remove this (temporary) and somewhat
|
||||
// misleading workaround.
|
||||
if compressed.len() > max_uncompressed_length {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
|
||||
let uncompressed =
|
||||
inflate::decompress_to_vec_zlib(&compressed).map_err(TiffError::from_inflate_status)?;
|
||||
|
||||
Ok((
|
||||
uncompressed.len(),
|
||||
Self {
|
||||
byte_order,
|
||||
buffer: io::Cursor::new(uncompressed),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for DeflateReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
self.buffer.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl EndianReader for DeflateReader {
|
||||
fn byte_order(&self) -> ByteOrder {
|
||||
self.byte_order
|
||||
}
|
||||
}
|
||||
pub type DeflateReader<'r, R> = flate2::read::ZlibDecoder<&'r mut SmartReader<R>>;
|
||||
|
||||
///
|
||||
/// ## LZW Reader
|
||||
@@ -248,7 +133,6 @@ impl EndianReader for DeflateReader {
|
||||
/// Reader that decompresses LZW streams
|
||||
pub struct LZWReader {
|
||||
buffer: io::Cursor<Vec<u8>>,
|
||||
byte_order: ByteOrder,
|
||||
}
|
||||
|
||||
impl LZWReader {
|
||||
@@ -261,25 +145,21 @@ impl LZWReader {
|
||||
where
|
||||
R: Read + Seek,
|
||||
{
|
||||
let order = reader.byte_order;
|
||||
let mut compressed = vec![0; compressed_length as usize];
|
||||
reader.read_exact(&mut compressed[..])?;
|
||||
let mut uncompressed = Vec::with_capacity(max_uncompressed_length);
|
||||
let mut uncompressed = vec![0; max_uncompressed_length];
|
||||
let mut decoder = weezl::decode::Decoder::with_tiff_size_switch(weezl::BitOrder::Msb, 8);
|
||||
|
||||
let mut bytes_read = 0;
|
||||
let mut bytes_written = 0;
|
||||
|
||||
while uncompressed.len() < max_uncompressed_length {
|
||||
let bytes_written = uncompressed.len();
|
||||
uncompressed.reserve(1 << 12);
|
||||
let buffer_space = uncompressed.capacity().min(max_uncompressed_length);
|
||||
uncompressed.resize(buffer_space, 0u8);
|
||||
|
||||
while bytes_written < max_uncompressed_length {
|
||||
let result = decoder.decode_bytes(
|
||||
&compressed[bytes_read..],
|
||||
&mut uncompressed[bytes_written..],
|
||||
);
|
||||
bytes_read += result.consumed_in;
|
||||
uncompressed.truncate(bytes_written + result.consumed_out);
|
||||
bytes_written += result.consumed_out;
|
||||
|
||||
match result.status {
|
||||
Ok(weezl::LzwStatus::Ok) => {}
|
||||
@@ -294,12 +174,11 @@ impl LZWReader {
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = uncompressed.len();
|
||||
uncompressed.resize(bytes_written, 0);
|
||||
Ok((
|
||||
bytes,
|
||||
uncompressed.len(),
|
||||
LZWReader {
|
||||
buffer: io::Cursor::new(uncompressed),
|
||||
byte_order: order,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -312,20 +191,12 @@ impl Read for LZWReader {
|
||||
}
|
||||
}
|
||||
|
||||
impl EndianReader for LZWReader {
|
||||
#[inline(always)]
|
||||
fn byte_order(&self) -> ByteOrder {
|
||||
self.byte_order
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// ## JPEG Reader (for "new-style" JPEG format (TIFF compression tag 7))
|
||||
///
|
||||
|
||||
pub(crate) struct JpegReader {
|
||||
buffer: io::Cursor<Vec<u8>>,
|
||||
byte_order: ByteOrder,
|
||||
}
|
||||
impl JpegReader {
|
||||
/// Constructs new JpegReader wrapping a SmartReader.
|
||||
@@ -348,8 +219,6 @@ impl JpegReader {
|
||||
where
|
||||
R: Read + Seek,
|
||||
{
|
||||
let order = reader.byte_order;
|
||||
|
||||
// Read jpeg image data
|
||||
let mut segment = vec![0; length as usize];
|
||||
reader.read_exact(&mut segment[..])?;
|
||||
@@ -359,16 +228,14 @@ impl JpegReader {
|
||||
let mut jpeg_data = tables.clone();
|
||||
let truncated_length = jpeg_data.len() - 2;
|
||||
jpeg_data.truncate(truncated_length);
|
||||
jpeg_data.extend_from_slice(&mut segment[2..]);
|
||||
jpeg_data.extend_from_slice(&segment[2..]);
|
||||
|
||||
Ok(JpegReader {
|
||||
buffer: io::Cursor::new(jpeg_data),
|
||||
byte_order: order,
|
||||
})
|
||||
}
|
||||
None => Ok(JpegReader {
|
||||
buffer: io::Cursor::new(segment),
|
||||
byte_order: order,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -381,13 +248,6 @@ impl Read for JpegReader {
|
||||
}
|
||||
}
|
||||
|
||||
impl EndianReader for JpegReader {
|
||||
#[inline(always)]
|
||||
fn byte_order(&self) -> ByteOrder {
|
||||
self.byte_order
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// ## PackBits Reader
|
||||
///
|
||||
@@ -395,58 +255,46 @@ impl EndianReader for JpegReader {
|
||||
/// Reader that unpacks Apple's `PackBits` format
|
||||
pub struct PackBitsReader {
|
||||
buffer: io::Cursor<Vec<u8>>,
|
||||
byte_order: ByteOrder,
|
||||
}
|
||||
|
||||
impl PackBitsReader {
|
||||
/// Wraps a reader
|
||||
pub fn new<R: Read + Seek>(
|
||||
mut reader: R,
|
||||
byte_order: ByteOrder,
|
||||
length: usize,
|
||||
) -> io::Result<(usize, PackBitsReader)> {
|
||||
let mut buffer = Vec::new();
|
||||
let mut read: usize = 0;
|
||||
while read < length {
|
||||
let lread = read_packbits_run(&mut reader, &mut buffer)?;
|
||||
if lread == 0 {
|
||||
return Err(io::ErrorKind::UnexpectedEof.into());
|
||||
}
|
||||
read += lread;
|
||||
}
|
||||
Ok((
|
||||
buffer.len(),
|
||||
PackBitsReader {
|
||||
buffer: io::Cursor::new(buffer),
|
||||
byte_order,
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
let mut header: [u8; 1] = [0];
|
||||
let mut data: [u8; 1] = [0];
|
||||
|
||||
fn read_packbits_run<R: Read + Seek>(reader: &mut R, buffer: &mut Vec<u8>) -> io::Result<usize> {
|
||||
let mut header: [u8; 1] = [0];
|
||||
let mut bytes_read = 0;
|
||||
while bytes_read < length {
|
||||
reader.read_exact(&mut header)?;
|
||||
bytes_read += 1;
|
||||
|
||||
let bytes = reader.read(&mut header)?;
|
||||
|
||||
match bytes {
|
||||
0 => Ok(0),
|
||||
_ => match header[0] as i8 {
|
||||
-128 => Ok(1),
|
||||
h if h >= -127 && h <= -1 => {
|
||||
let h = header[0] as i8;
|
||||
if h >= -127 && h <= -1 {
|
||||
let new_len = buffer.len() + (1 - h as isize) as usize;
|
||||
reader.read_exact(&mut header)?;
|
||||
buffer.resize(new_len, header[0]);
|
||||
Ok(2)
|
||||
}
|
||||
h => {
|
||||
reader.read_exact(&mut data)?;
|
||||
buffer.resize(new_len, data[0]);
|
||||
bytes_read += 1;
|
||||
} else if h >= 0 {
|
||||
let num_vals = h as usize + 1;
|
||||
let start = buffer.len();
|
||||
buffer.resize(start + num_vals, 0);
|
||||
reader.read_exact(&mut buffer[start..])?;
|
||||
Ok(num_vals + 1)
|
||||
bytes_read += num_vals
|
||||
} else {
|
||||
// h = -128 is a no-op.
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
Ok((
|
||||
buffer.len(),
|
||||
PackBitsReader {
|
||||
buffer: io::Cursor::new(buffer),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,13 +305,6 @@ impl Read for PackBitsReader {
|
||||
}
|
||||
}
|
||||
|
||||
impl EndianReader for PackBitsReader {
|
||||
#[inline(always)]
|
||||
fn byte_order(&self) -> ByteOrder {
|
||||
self.byte_order
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// ## SmartReader Reader
|
||||
///
|
||||
@@ -472,7 +313,7 @@ impl EndianReader for PackBitsReader {
|
||||
#[derive(Debug)]
|
||||
pub struct SmartReader<R>
|
||||
where
|
||||
R: Read + Seek,
|
||||
R: Read,
|
||||
{
|
||||
reader: R,
|
||||
pub byte_order: ByteOrder,
|
||||
@@ -480,7 +321,7 @@ where
|
||||
|
||||
impl<R> SmartReader<R>
|
||||
where
|
||||
R: Read + Seek,
|
||||
R: Read,
|
||||
{
|
||||
/// Wraps a reader
|
||||
pub fn wrap(reader: R, byte_order: ByteOrder) -> SmartReader<R> {
|
||||
@@ -490,7 +331,7 @@ where
|
||||
|
||||
impl<R> EndianReader for SmartReader<R>
|
||||
where
|
||||
R: Read + Seek,
|
||||
R: Read,
|
||||
{
|
||||
#[inline(always)]
|
||||
fn byte_order(&self) -> ByteOrder {
|
||||
@@ -498,7 +339,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> Read for SmartReader<R> {
|
||||
impl<R: Read> Read for SmartReader<R> {
|
||||
#[inline]
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
self.reader.read(buf)
|
||||
@@ -525,8 +366,7 @@ mod test {
|
||||
let encoded_len = encoded.len();
|
||||
|
||||
let buff = io::Cursor::new(encoded);
|
||||
let (_, mut decoder) =
|
||||
PackBitsReader::new(buff, ByteOrder::LittleEndian, encoded_len).unwrap();
|
||||
let (_, mut decoder) = PackBitsReader::new(buff, encoded_len).unwrap();
|
||||
|
||||
let mut decoded = Vec::new();
|
||||
decoder.read_to_end(&mut decoded).unwrap();
|
||||
|
||||
+227
-437
@@ -1,402 +1,31 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::io::{Seek, Write};
|
||||
use std::{cmp, io, mem};
|
||||
pub use tiff_value::*;
|
||||
|
||||
use crate::bytecast;
|
||||
use crate::error::{TiffError, TiffFormatError, TiffResult};
|
||||
use crate::tags::{self, ResolutionUnit, Tag, Type};
|
||||
use std::{
|
||||
cmp,
|
||||
collections::BTreeMap,
|
||||
convert::{TryFrom, TryInto},
|
||||
io::{self, Seek, Write},
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
num::TryFromIntError,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
error::TiffResult,
|
||||
tags::{self, ResolutionUnit, Tag},
|
||||
};
|
||||
|
||||
pub mod colortype;
|
||||
mod tiff_value;
|
||||
mod writer;
|
||||
|
||||
use self::colortype::*;
|
||||
use self::writer::*;
|
||||
|
||||
/// Type to represent tiff values of type `RATIONAL`
|
||||
#[derive(Clone)]
|
||||
pub struct Rational {
|
||||
pub n: u32,
|
||||
pub d: u32,
|
||||
}
|
||||
|
||||
/// Type to represent tiff values of type `SRATIONAL`
|
||||
pub struct SRational {
|
||||
pub n: i32,
|
||||
pub d: i32,
|
||||
}
|
||||
|
||||
/// Trait for types that can be encoded in a tiff file
|
||||
pub trait TiffValue {
|
||||
const BYTE_LEN: u32;
|
||||
const FIELD_TYPE: Type;
|
||||
fn count(&self) -> u32;
|
||||
fn bytes(&self) -> u32 {
|
||||
self.count() * Self::BYTE_LEN
|
||||
}
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()>;
|
||||
}
|
||||
|
||||
impl TiffValue for [u8] {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_bytes(self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i8] {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: Type = Type::SBYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i8_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u16] {
|
||||
const BYTE_LEN: u32 = 2;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u16_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i16] {
|
||||
const BYTE_LEN: u32 = 2;
|
||||
const FIELD_TYPE: Type = Type::SSHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i16_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u32] {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i32] {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::SLONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u64] {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::LONG8;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u64_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [f32] {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::FLOAT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
// We write using nativeedian so this sould be safe
|
||||
let slice = bytecast::f32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [f64] {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::DOUBLE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
// We write using nativeedian so this sould be safe
|
||||
let slice = bytecast::f64_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [Rational] {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::RATIONAL;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [SRational] {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::SRATIONAL;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u8 {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u8(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i8 {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: Type = Type::SBYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i8(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u16 {
|
||||
const BYTE_LEN: u32 = 2;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u16(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i16 {
|
||||
const BYTE_LEN: u32 = 2;
|
||||
const FIELD_TYPE: Type = Type::SSHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i16(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u32 {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i32 {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::SLONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u64 {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::LONG8;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u64(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for f32 {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: Type = Type::FLOAT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_f32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for f64 {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::DOUBLE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_f64(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for Rational {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::RATIONAL;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u32(self.n)?;
|
||||
writer.write_u32(self.d)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for SRational {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: Type = Type::SRATIONAL;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i32(self.n)?;
|
||||
writer.write_i32(self.d)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for str {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: Type = Type::ASCII;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32 + 1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
if self.is_ascii() && !self.bytes().any(|b| b == 0) {
|
||||
writer.write_bytes(self.as_bytes())?;
|
||||
writer.write_u8(0)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TiffError::FormatError(TiffFormatError::InvalidTag))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
|
||||
const BYTE_LEN: u32 = T::BYTE_LEN;
|
||||
const FIELD_TYPE: Type = T::FIELD_TYPE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
(*self).count()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
(*self).write(writer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiff encoder.
|
||||
/// Encoder for Tiff and BigTiff files.
|
||||
///
|
||||
/// With this type you can get a `DirectoryEncoder` or a `ImageEncoder`
|
||||
/// to encode tiff ifd directories with images.
|
||||
/// to encode Tiff/BigTiff ifd directories with images.
|
||||
///
|
||||
/// See `DirectoryEncoder` and `ImageEncoder`.
|
||||
///
|
||||
@@ -408,39 +37,68 @@ impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
|
||||
/// # let image_data = vec![0; 100*100*3];
|
||||
/// use tiff::encoder::*;
|
||||
///
|
||||
/// // create a standard Tiff file
|
||||
/// let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
///
|
||||
/// tiff.write_image::<colortype::RGB8>(100, 100, &image_data).unwrap();
|
||||
///
|
||||
/// // create a BigTiff file
|
||||
/// let mut bigtiff = TiffEncoder::new_big(&mut file).unwrap();
|
||||
/// bigtiff.write_image::<colortype::RGB8>(100, 100, &image_data).unwrap();
|
||||
///
|
||||
/// # }
|
||||
/// ```
|
||||
pub struct TiffEncoder<W> {
|
||||
pub struct TiffEncoder<W, K: TiffKind = TiffKindStandard> {
|
||||
writer: TiffWriter<W>,
|
||||
kind: PhantomData<K>,
|
||||
}
|
||||
|
||||
/// Constructor functions to create standard Tiff files.
|
||||
impl<W: Write + Seek> TiffEncoder<W> {
|
||||
pub fn new(writer: W) -> TiffResult<TiffEncoder<W>> {
|
||||
/// Creates a new encoder for standard Tiff files.
|
||||
///
|
||||
/// To create BigTiff files, use [`new_big`][TiffEncoder::new_big] or
|
||||
/// [`new_generic`][TiffEncoder::new_generic].
|
||||
pub fn new(writer: W) -> TiffResult<TiffEncoder<W, TiffKindStandard>> {
|
||||
TiffEncoder::new_generic(writer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructor functions to create BigTiff files.
|
||||
impl<W: Write + Seek> TiffEncoder<W, TiffKindBig> {
|
||||
/// Creates a new encoder for BigTiff files.
|
||||
///
|
||||
/// To create standard Tiff files, use [`new`][TiffEncoder::new] or
|
||||
/// [`new_generic`][TiffEncoder::new_generic].
|
||||
pub fn new_big(writer: W) -> TiffResult<Self> {
|
||||
TiffEncoder::new_generic(writer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic functions that are available for both Tiff and BigTiff encoders.
|
||||
impl<W: Write + Seek, K: TiffKind> TiffEncoder<W, K> {
|
||||
/// Creates a new Tiff or BigTiff encoder, inferred from the return type.
|
||||
pub fn new_generic(writer: W) -> TiffResult<Self> {
|
||||
let mut encoder = TiffEncoder {
|
||||
writer: TiffWriter::new(writer),
|
||||
kind: PhantomData,
|
||||
};
|
||||
|
||||
write_tiff_header(&mut encoder.writer)?;
|
||||
// blank the IFD offset location
|
||||
encoder.writer.write_u32(0)?;
|
||||
K::write_header(&mut encoder.writer)?;
|
||||
|
||||
Ok(encoder)
|
||||
}
|
||||
|
||||
/// Create a `DirectoryEncoder` to encode an ifd directory.
|
||||
pub fn new_directory(&mut self) -> TiffResult<DirectoryEncoder<W>> {
|
||||
/// Create a [`DirectoryEncoder`] to encode an ifd directory.
|
||||
pub fn new_directory(&mut self) -> TiffResult<DirectoryEncoder<W, K>> {
|
||||
DirectoryEncoder::new(&mut self.writer)
|
||||
}
|
||||
|
||||
/// Create an 'ImageEncoder' to encode an image one slice at a time.
|
||||
/// Create an [`ImageEncoder`] to encode an image one slice at a time.
|
||||
pub fn new_image<C: ColorType>(
|
||||
&mut self,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> TiffResult<ImageEncoder<W, C>> {
|
||||
) -> TiffResult<ImageEncoder<W, C, K>> {
|
||||
let encoder = DirectoryEncoder::new(&mut self.writer)?;
|
||||
ImageEncoder::new(encoder, width, height)
|
||||
}
|
||||
@@ -456,7 +114,7 @@ impl<W: Write + Seek> TiffEncoder<W> {
|
||||
[C::Inner]: TiffValue,
|
||||
{
|
||||
let encoder = DirectoryEncoder::new(&mut self.writer)?;
|
||||
let image: ImageEncoder<W, C> = ImageEncoder::new(encoder, width, height)?;
|
||||
let image: ImageEncoder<W, C, K> = ImageEncoder::new(encoder, width, height)?;
|
||||
image.write_data(data)
|
||||
}
|
||||
}
|
||||
@@ -465,19 +123,19 @@ impl<W: Write + Seek> TiffEncoder<W> {
|
||||
///
|
||||
/// You should call `finish` on this when you are finished with it.
|
||||
/// Encoding can silently fail while this is dropping.
|
||||
pub struct DirectoryEncoder<'a, W: 'a + Write + Seek> {
|
||||
pub struct DirectoryEncoder<'a, W: 'a + Write + Seek, K: TiffKind> {
|
||||
writer: &'a mut TiffWriter<W>,
|
||||
dropped: bool,
|
||||
// We use BTreeMap to make sure tags are written in correct order
|
||||
ifd_pointer_pos: u64,
|
||||
ifd: BTreeMap<u16, (u16, u32, Vec<u8>)>,
|
||||
ifd: BTreeMap<u16, DirectoryEntry<K::OffsetType>>,
|
||||
}
|
||||
|
||||
impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
fn new(writer: &'a mut TiffWriter<W>) -> TiffResult<DirectoryEncoder<'a, W>> {
|
||||
impl<'a, W: 'a + Write + Seek, K: TiffKind> DirectoryEncoder<'a, W, K> {
|
||||
fn new(writer: &'a mut TiffWriter<W>) -> TiffResult<Self> {
|
||||
// the previous word is the IFD offset position
|
||||
let ifd_pointer_pos = writer.offset() - mem::size_of::<u32>() as u64;
|
||||
writer.pad_word_boundary()?;
|
||||
let ifd_pointer_pos = writer.offset() - mem::size_of::<K::OffsetType>() as u64;
|
||||
writer.pad_word_boundary()?; // TODO: Do we need to adjust this for BigTiff?
|
||||
Ok(DirectoryEncoder {
|
||||
writer,
|
||||
dropped: false,
|
||||
@@ -488,8 +146,7 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
|
||||
/// Write a single ifd tag.
|
||||
pub fn write_tag<T: TiffValue>(&mut self, tag: Tag, value: T) -> TiffResult<()> {
|
||||
let len = <T>::BYTE_LEN * value.count();
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(len)?);
|
||||
let mut bytes = Vec::with_capacity(value.bytes());
|
||||
{
|
||||
let mut writer = TiffWriter::new(&mut bytes);
|
||||
value.write(&mut writer)?;
|
||||
@@ -497,7 +154,11 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
|
||||
self.ifd.insert(
|
||||
tag.to_u16(),
|
||||
(<T>::FIELD_TYPE.to_u16(), value.count(), bytes),
|
||||
DirectoryEntry {
|
||||
data_type: <T>::FIELD_TYPE.to_u16(),
|
||||
count: value.count().try_into()?,
|
||||
data: bytes,
|
||||
},
|
||||
);
|
||||
|
||||
Ok(())
|
||||
@@ -505,15 +166,21 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
|
||||
fn write_directory(&mut self) -> TiffResult<u64> {
|
||||
// Start by writing out all values
|
||||
for &mut (_, _, ref mut bytes) in self.ifd.values_mut() {
|
||||
if bytes.len() > 4 {
|
||||
for &mut DirectoryEntry {
|
||||
data: ref mut bytes,
|
||||
..
|
||||
} in self.ifd.values_mut()
|
||||
{
|
||||
let data_bytes = mem::size_of::<K::OffsetType>();
|
||||
|
||||
if bytes.len() > data_bytes {
|
||||
let offset = self.writer.offset();
|
||||
self.writer.write_bytes(bytes)?;
|
||||
*bytes = vec![0, 0, 0, 0];
|
||||
*bytes = vec![0; data_bytes];
|
||||
let mut writer = TiffWriter::new(bytes as &mut [u8]);
|
||||
writer.write_u32(u32::try_from(offset)?)?;
|
||||
K::write_offset(&mut writer, offset)?;
|
||||
} else {
|
||||
while bytes.len() < 4 {
|
||||
while bytes.len() < data_bytes {
|
||||
bytes.push(0);
|
||||
}
|
||||
}
|
||||
@@ -521,11 +188,19 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
|
||||
let offset = self.writer.offset();
|
||||
|
||||
self.writer.write_u16(u16::try_from(self.ifd.len())?)?;
|
||||
for (tag, &(ref field_type, ref count, ref offset)) in self.ifd.iter() {
|
||||
K::write_entry_count(&mut self.writer, self.ifd.len())?;
|
||||
for (
|
||||
tag,
|
||||
&DirectoryEntry {
|
||||
data_type: ref field_type,
|
||||
ref count,
|
||||
data: ref offset,
|
||||
},
|
||||
) in self.ifd.iter()
|
||||
{
|
||||
self.writer.write_u16(*tag)?;
|
||||
self.writer.write_u16(*field_type)?;
|
||||
self.writer.write_u32(*count)?;
|
||||
(*count).write(&mut self.writer)?;
|
||||
self.writer.write_bytes(offset)?;
|
||||
}
|
||||
|
||||
@@ -546,9 +221,9 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
let curr_pos = self.writer.offset();
|
||||
|
||||
self.writer.goto_offset(self.ifd_pointer_pos)?;
|
||||
self.writer.write_u32(u32::try_from(ifd_pointer)?)?;
|
||||
K::write_offset(&mut self.writer, ifd_pointer)?;
|
||||
self.writer.goto_offset(curr_pos)?;
|
||||
self.writer.write_u32(0)?;
|
||||
K::write_offset(&mut self.writer, 0)?;
|
||||
|
||||
self.dropped = true;
|
||||
|
||||
@@ -561,7 +236,7 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, W: Write + Seek> Drop for DirectoryEncoder<'a, W> {
|
||||
impl<'a, W: Write + Seek, K: TiffKind> Drop for DirectoryEncoder<'a, W, K> {
|
||||
fn drop(&mut self) {
|
||||
if !self.dropped {
|
||||
let _ = self.finish_internal();
|
||||
@@ -602,26 +277,22 @@ impl<'a, W: Write + Seek> Drop for DirectoryEncoder<'a, W> {
|
||||
/// # }
|
||||
/// ```
|
||||
/// You can also call write_data function wich will encode by strip and finish
|
||||
pub struct ImageEncoder<'a, W: 'a + Write + Seek, C: ColorType> {
|
||||
encoder: DirectoryEncoder<'a, W>,
|
||||
pub struct ImageEncoder<'a, W: 'a + Write + Seek, C: ColorType, K: TiffKind> {
|
||||
encoder: DirectoryEncoder<'a, W, K>,
|
||||
strip_idx: u64,
|
||||
strip_count: u64,
|
||||
row_samples: u64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
rows_per_strip: u64,
|
||||
strip_offsets: Vec<u32>,
|
||||
strip_byte_count: Vec<u32>,
|
||||
strip_offsets: Vec<K::OffsetType>,
|
||||
strip_byte_count: Vec<K::OffsetType>,
|
||||
dropped: bool,
|
||||
_phantom: ::std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
fn new(
|
||||
mut encoder: DirectoryEncoder<'a, W>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> TiffResult<ImageEncoder<'a, W, T>> {
|
||||
impl<'a, W: 'a + Write + Seek, T: ColorType, K: TiffKind> ImageEncoder<'a, W, T, K> {
|
||||
fn new(mut encoder: DirectoryEncoder<'a, W, K>, width: u32, height: u32) -> TiffResult<Self> {
|
||||
let row_samples = u64::from(width) * u64::try_from(<T>::BITS_PER_SAMPLE.len())?;
|
||||
let row_bytes = row_samples * u64::from(<T::Inner>::BYTE_LEN);
|
||||
|
||||
@@ -694,8 +365,8 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
}
|
||||
|
||||
let offset = self.encoder.write_data(value)?;
|
||||
self.strip_offsets.push(u32::try_from(offset)?);
|
||||
self.strip_byte_count.push(value.bytes());
|
||||
self.strip_offsets.push(K::convert_offset(offset)?);
|
||||
self.strip_byte_count.push(value.bytes().try_into()?);
|
||||
|
||||
self.strip_idx += 1;
|
||||
Ok(())
|
||||
@@ -783,16 +454,18 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
|
||||
fn finish_internal(&mut self) -> TiffResult<()> {
|
||||
self.encoder
|
||||
.write_tag(Tag::StripOffsets, &*self.strip_offsets)?;
|
||||
self.encoder
|
||||
.write_tag(Tag::StripByteCounts, &*self.strip_byte_count)?;
|
||||
.write_tag(Tag::StripOffsets, K::convert_slice(&self.strip_offsets))?;
|
||||
self.encoder.write_tag(
|
||||
Tag::StripByteCounts,
|
||||
K::convert_slice(&self.strip_byte_count),
|
||||
)?;
|
||||
self.dropped = true;
|
||||
|
||||
self.encoder.finish_internal()
|
||||
}
|
||||
|
||||
/// Get a reference of the underlying `DirectoryEncoder`
|
||||
pub fn encoder(&mut self) -> &mut DirectoryEncoder<'a, W> {
|
||||
pub fn encoder(&mut self) -> &mut DirectoryEncoder<'a, W, K> {
|
||||
&mut self.encoder
|
||||
}
|
||||
|
||||
@@ -802,10 +475,127 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, W: Write + Seek, C: ColorType> Drop for ImageEncoder<'a, W, C> {
|
||||
impl<'a, W: Write + Seek, C: ColorType, K: TiffKind> Drop for ImageEncoder<'a, W, C, K> {
|
||||
fn drop(&mut self) {
|
||||
if !self.dropped {
|
||||
let _ = self.finish_internal();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DirectoryEntry<S> {
|
||||
data_type: u16,
|
||||
count: S,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Trait to abstract over Tiff/BigTiff differences.
|
||||
///
|
||||
/// Implemented for [`TiffKindStandard`] and [`TiffKindBig`].
|
||||
pub trait TiffKind {
|
||||
/// The type of offset fields, `u32` for normal Tiff, `u64` for BigTiff.
|
||||
type OffsetType: TryFrom<usize, Error = TryFromIntError> + Into<u64> + TiffValue;
|
||||
|
||||
/// Needed for the `convert_slice` method.
|
||||
type OffsetArrayType: ?Sized + TiffValue;
|
||||
|
||||
/// Write the (Big)Tiff header.
|
||||
fn write_header<W: Write>(writer: &mut TiffWriter<W>) -> TiffResult<()>;
|
||||
|
||||
/// Convert a file offset to `Self::OffsetType`.
|
||||
///
|
||||
/// This returns an error for normal Tiff if the offset is larger than `u32::MAX`.
|
||||
fn convert_offset(offset: u64) -> TiffResult<Self::OffsetType>;
|
||||
|
||||
/// Write an offset value to the given writer.
|
||||
///
|
||||
/// Like `convert_offset`, this errors if `offset > u32::MAX` for normal Tiff.
|
||||
fn write_offset<W: Write>(writer: &mut TiffWriter<W>, offset: u64) -> TiffResult<()>;
|
||||
|
||||
/// Write the IFD entry count field with the given `count` value.
|
||||
///
|
||||
/// The entry count field is an `u16` for normal Tiff and `u64` for BigTiff. Errors
|
||||
/// if the given `usize` is larger than the representable values.
|
||||
fn write_entry_count<W: Write>(writer: &mut TiffWriter<W>, count: usize) -> TiffResult<()>;
|
||||
|
||||
/// Internal helper method for satisfying Rust's type checker.
|
||||
///
|
||||
/// The `TiffValue` trait is implemented for both primitive values (e.g. `u8`, `u32`) and
|
||||
/// slices of primitive values (e.g. `[u8]`, `[u32]`). However, this is not represented in
|
||||
/// the type system, so there is no guarantee that that for all `T: TiffValue` there is also
|
||||
/// an implementation of `TiffValue` for `[T]`. This method works around that problem by
|
||||
/// providing a conversion from `[T]` to some value that implements `TiffValue`, thereby
|
||||
/// making all slices of `OffsetType` usable with `write_tag` and similar methods.
|
||||
///
|
||||
/// Implementations of this trait should always set `OffsetArrayType` to `[OffsetType]`.
|
||||
fn convert_slice(slice: &[Self::OffsetType]) -> &Self::OffsetArrayType;
|
||||
}
|
||||
|
||||
/// Create a standard Tiff file.
|
||||
pub struct TiffKindStandard;
|
||||
|
||||
impl TiffKind for TiffKindStandard {
|
||||
type OffsetType = u32;
|
||||
type OffsetArrayType = [u32];
|
||||
|
||||
fn write_header<W: Write>(writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
write_tiff_header(writer)?;
|
||||
// blank the IFD offset location
|
||||
writer.write_u32(0)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_offset(offset: u64) -> TiffResult<Self::OffsetType> {
|
||||
Ok(Self::OffsetType::try_from(offset)?)
|
||||
}
|
||||
|
||||
fn write_offset<W: Write>(writer: &mut TiffWriter<W>, offset: u64) -> TiffResult<()> {
|
||||
writer.write_u32(u32::try_from(offset)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_entry_count<W: Write>(writer: &mut TiffWriter<W>, count: usize) -> TiffResult<()> {
|
||||
writer.write_u16(u16::try_from(count)?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_slice(slice: &[Self::OffsetType]) -> &Self::OffsetArrayType {
|
||||
slice
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a BigTiff file.
|
||||
pub struct TiffKindBig;
|
||||
|
||||
impl TiffKind for TiffKindBig {
|
||||
type OffsetType = u64;
|
||||
type OffsetArrayType = [u64];
|
||||
|
||||
fn write_header<W: Write>(writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
write_bigtiff_header(writer)?;
|
||||
// blank the IFD offset location
|
||||
writer.write_u64(0)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_offset(offset: u64) -> TiffResult<Self::OffsetType> {
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
fn write_offset<W: Write>(writer: &mut TiffWriter<W>, offset: u64) -> TiffResult<()> {
|
||||
writer.write_u64(offset)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_entry_count<W: Write>(writer: &mut TiffWriter<W>, count: usize) -> TiffResult<()> {
|
||||
writer.write_u64(u64::try_from(count)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert_slice(slice: &[Self::OffsetType]) -> &Self::OffsetArrayType {
|
||||
slice
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
use std::io::Write;
|
||||
|
||||
use crate::{bytecast, tags::Type, TiffError, TiffFormatError, TiffResult};
|
||||
|
||||
use super::writer::TiffWriter;
|
||||
|
||||
/// Trait for types that can be encoded in a tiff file
|
||||
pub trait TiffValue {
|
||||
const BYTE_LEN: u8;
|
||||
const FIELD_TYPE: Type;
|
||||
fn count(&self) -> usize;
|
||||
fn bytes(&self) -> usize {
|
||||
self.count() * usize::from(Self::BYTE_LEN)
|
||||
}
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()>;
|
||||
}
|
||||
|
||||
impl TiffValue for [u8] {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_bytes(self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i8] {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: Type = Type::SBYTE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i8_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u16] {
|
||||
const BYTE_LEN: u8 = 2;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u16_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i16] {
|
||||
const BYTE_LEN: u8 = 2;
|
||||
const FIELD_TYPE: Type = Type::SSHORT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i16_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u32] {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i32] {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::SLONG;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u64] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::LONG8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::u64_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [i64] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::SLONG8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
let slice = bytecast::i64_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [f32] {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::FLOAT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
// We write using nativeedian so this sould be safe
|
||||
let slice = bytecast::f32_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [f64] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::DOUBLE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
// We write using nativeedian so this sould be safe
|
||||
let slice = bytecast::f64_as_ne_bytes(self);
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [Ifd] {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::IFD;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [Ifd8] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::IFD8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [Rational] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::RATIONAL;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [SRational] {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::SRATIONAL;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
for x in self {
|
||||
x.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u8 {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u8(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i8 {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: Type = Type::SBYTE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i8(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u16 {
|
||||
const BYTE_LEN: u8 = 2;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u16(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i16 {
|
||||
const BYTE_LEN: u8 = 2;
|
||||
const FIELD_TYPE: Type = Type::SSHORT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i16(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u32 {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i32 {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::SLONG;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for u64 {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::LONG8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u64(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for i64 {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::SLONG8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i64(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for f32 {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::FLOAT;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_f32(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for f64 {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::DOUBLE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_f64(*self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for Ifd {
|
||||
const BYTE_LEN: u8 = 4;
|
||||
const FIELD_TYPE: Type = Type::IFD;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u32(self.0)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for Ifd8 {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::IFD8;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u64(self.0)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for Rational {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::RATIONAL;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_u32(self.n)?;
|
||||
writer.write_u32(self.d)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for SRational {
|
||||
const BYTE_LEN: u8 = 8;
|
||||
const FIELD_TYPE: Type = Type::SRATIONAL;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
writer.write_i32(self.n)?;
|
||||
writer.write_i32(self.d)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for str {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: Type = Type::ASCII;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.len() + 1
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
if self.is_ascii() && !self.bytes().any(|b| b == 0) {
|
||||
writer.write_bytes(self.as_bytes())?;
|
||||
writer.write_u8(0)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TiffError::FormatError(TiffFormatError::InvalidTag))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
|
||||
const BYTE_LEN: u8 = T::BYTE_LEN;
|
||||
const FIELD_TYPE: Type = T::FIELD_TYPE;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
(*self).count()
|
||||
}
|
||||
|
||||
fn write<W: Write>(&self, writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
(*self).write(writer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Type to represent tiff values of type `IFD`
|
||||
#[derive(Clone)]
|
||||
pub struct Ifd(pub u32);
|
||||
|
||||
/// Type to represent tiff values of type `IFD8`
|
||||
#[derive(Clone)]
|
||||
pub struct Ifd8(pub u64);
|
||||
|
||||
/// Type to represent tiff values of type `RATIONAL`
|
||||
#[derive(Clone)]
|
||||
pub struct Rational {
|
||||
pub n: u32,
|
||||
pub d: u32,
|
||||
}
|
||||
|
||||
/// Type to represent tiff values of type `SRATIONAL`
|
||||
#[derive(Clone)]
|
||||
pub struct SRational {
|
||||
pub n: i32,
|
||||
pub d: i32,
|
||||
}
|
||||
@@ -14,6 +14,31 @@ pub fn write_tiff_header<W: Write>(writer: &mut TiffWriter<W>) -> TiffResult<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes a BigTiff header, excluding the IFD offset field.
|
||||
///
|
||||
/// Writes the byte order, version number, offset byte size, and zero constant fields. Does
|
||||
// _not_ write the offset to the first IFD, this should be done by the caller.
|
||||
pub fn write_bigtiff_header<W: Write>(writer: &mut TiffWriter<W>) -> TiffResult<()> {
|
||||
#[cfg(target_endian = "little")]
|
||||
let boi: u8 = 0x49;
|
||||
#[cfg(not(target_endian = "little"))]
|
||||
let boi: u8 = 0x4d;
|
||||
|
||||
// byte order indication
|
||||
writer.writer.write_all(&[boi, boi])?;
|
||||
// version number
|
||||
writer.writer.write_all(&43u16.to_ne_bytes())?;
|
||||
// bytesize of offsets (pointer size)
|
||||
writer.writer.write_all(&8u16.to_ne_bytes())?;
|
||||
// always 0
|
||||
writer.writer.write_all(&0u16.to_ne_bytes())?;
|
||||
|
||||
// we wrote 8 bytes, so set the internal offset accordingly
|
||||
writer.offset += 8;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct TiffWriter<W> {
|
||||
writer: W,
|
||||
offset: u64,
|
||||
@@ -81,6 +106,13 @@ impl<W: Write> TiffWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_i64(&mut self, n: i64) -> Result<(), io::Error> {
|
||||
self.writer.write_all(&n.to_ne_bytes())?;
|
||||
self.offset += 8;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_f32(&mut self, n: f32) -> Result<(), io::Error> {
|
||||
self.writer.write_all(&u32::to_ne_bytes(n.to_bits()))?;
|
||||
self.offset += 4;
|
||||
|
||||
+36
-22
@@ -1,14 +1,14 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::str;
|
||||
use std::string;
|
||||
|
||||
use crate::decoder::ifd::Value;
|
||||
use crate::decoder::{ifd::Value, ChunkType};
|
||||
use crate::tags::{
|
||||
CompressionMethod, PhotometricInterpretation, PlanarConfiguration, SampleFormat, Tag,
|
||||
};
|
||||
use crate::ColorType;
|
||||
use miniz_oxide::inflate::TINFLStatus;
|
||||
|
||||
/// Tiff error kinds.
|
||||
#[derive(Debug)]
|
||||
@@ -28,6 +28,9 @@ pub enum TiffError {
|
||||
/// An integer conversion to or from a platform size failed, either due to
|
||||
/// limits of the platform size or limits of the format.
|
||||
IntSizeError,
|
||||
|
||||
/// The image does not support the requested operation
|
||||
UsageError(UsageError),
|
||||
}
|
||||
|
||||
/// The image is not formatted properly.
|
||||
@@ -58,7 +61,6 @@ pub enum TiffFormatError {
|
||||
ByteExpected(Value),
|
||||
UnsignedIntegerExpected(Value),
|
||||
SignedIntegerExpected(Value),
|
||||
InflateError(InflateError),
|
||||
Format(String),
|
||||
RequiredTagEmpty(Tag),
|
||||
#[doc(hidden)]
|
||||
@@ -109,7 +111,6 @@ impl fmt::Display for TiffFormatError {
|
||||
SignedIntegerExpected(ref val) => {
|
||||
write!(fmt, "Expected signed integer, {:?} found.", val)
|
||||
}
|
||||
InflateError(_) => write!(fmt, "Failed to decode inflate data."),
|
||||
Format(ref val) => write!(fmt, "Invalid format: {:?}.", val),
|
||||
RequiredTagEmpty(ref val) => write!(fmt, "Required tag {:?} was empty.", val),
|
||||
__NonExhaustive => unreachable!(),
|
||||
@@ -117,24 +118,6 @@ impl fmt::Display for TiffFormatError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decompression failed due to faulty compressed data.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct InflateError {
|
||||
status: TINFLStatus,
|
||||
}
|
||||
|
||||
impl InflateError {
|
||||
pub(crate) fn new(status: TINFLStatus) -> Self {
|
||||
Self { status }
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffError {
|
||||
pub(crate) fn from_inflate_status(status: TINFLStatus) -> Self {
|
||||
TiffError::FormatError(TiffFormatError::InflateError(InflateError::new(status)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The Decoder does not support features required by the image.
|
||||
///
|
||||
/// This only captures known failures for which the standard either does not require support or an
|
||||
@@ -204,6 +187,29 @@ impl fmt::Display for TiffUnsupportedError {
|
||||
}
|
||||
}
|
||||
|
||||
/// User attempted to use the Decoder in a way that is incompatible with a specific image.
|
||||
///
|
||||
/// For example: attempting to read a tile from a stripped image.
|
||||
#[derive(Debug)]
|
||||
pub enum UsageError {
|
||||
InvalidChunkType(ChunkType, ChunkType),
|
||||
}
|
||||
|
||||
impl fmt::Display for UsageError {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
use self::UsageError::*;
|
||||
match *self {
|
||||
InvalidChunkType(expected, actual) => {
|
||||
write!(
|
||||
fmt,
|
||||
"Requested operation is only valid for images with chunk encoding of type: {:?}, got {:?}.",
|
||||
expected, actual
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for TiffError {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
match *self {
|
||||
@@ -217,6 +223,7 @@ impl fmt::Display for TiffError {
|
||||
TiffError::IoError(ref e) => e.fmt(fmt),
|
||||
TiffError::LimitsExceeded => write!(fmt, "The Decoder limits are exceeded"),
|
||||
TiffError::IntSizeError => write!(fmt, "Platform or format size limits exceeded"),
|
||||
TiffError::UsageError(ref e) => write!(fmt, "Usage error: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +236,7 @@ impl Error for TiffError {
|
||||
TiffError::IoError(..) => "IO error",
|
||||
TiffError::LimitsExceeded => "Decoder limits exceeded",
|
||||
TiffError::IntSizeError => "Platform or format size limits exceeded",
|
||||
TiffError::UsageError(..) => "Invalid usage",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +254,12 @@ impl From<io::Error> for TiffError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<str::Utf8Error> for TiffError {
|
||||
fn from(_err: str::Utf8Error) -> TiffError {
|
||||
TiffError::FormatError(TiffFormatError::InvalidTag)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<string::FromUtf8Error> for TiffError {
|
||||
fn from(_err: string::FromUtf8Error) -> TiffError {
|
||||
TiffError::FormatError(TiffFormatError::InvalidTag)
|
||||
|
||||
+1
-2
@@ -7,7 +7,6 @@
|
||||
//! * <https://www.adobe.io/open/standards/TIFF.html> - The TIFF specification
|
||||
|
||||
extern crate jpeg;
|
||||
extern crate miniz_oxide;
|
||||
extern crate weezl;
|
||||
|
||||
mod bytecast;
|
||||
@@ -16,7 +15,7 @@ pub mod encoder;
|
||||
mod error;
|
||||
pub mod tags;
|
||||
|
||||
pub use self::error::{InflateError, TiffError, TiffFormatError, TiffResult, TiffUnsupportedError};
|
||||
pub use self::error::{TiffError, TiffFormatError, TiffResult, TiffUnsupportedError, UsageError};
|
||||
|
||||
/// An enumeration over supported color types and their bit depths
|
||||
#[derive(Copy, PartialEq, Eq, Debug, Clone, Hash)]
|
||||
|
||||
+23
-2
@@ -111,15 +111,18 @@ pub enum Tag(u16) unknown("A private or extension tag") {
|
||||
Threshholding = 263, // TODO add support
|
||||
XResolution = 282,
|
||||
YResolution = 283,
|
||||
// JPEG
|
||||
JPEGTables = 347,
|
||||
// Advanced tags
|
||||
Predictor = 317,
|
||||
TileWidth = 322,
|
||||
TileLength = 323,
|
||||
TileOffsets = 324,
|
||||
TileByteCounts = 325,
|
||||
// Data Sample Format
|
||||
SampleFormat = 339,
|
||||
SMinSampleValue = 340, // TODO add support
|
||||
SMaxSampleValue = 341, // TODO add support
|
||||
// JPEG
|
||||
JPEGTables = 347,
|
||||
// GeoTIFF
|
||||
ModelPixelScaleTag = 33550, // (SoftDesk)
|
||||
ModelTransformationTag = 34264, // (JPL Carto Group)
|
||||
@@ -134,20 +137,38 @@ pub enum Tag(u16) unknown("A private or extension tag") {
|
||||
tags! {
|
||||
/// The type of an IFD entry (a 2 byte field).
|
||||
pub enum Type(u16) {
|
||||
/// 8-bit unsigned integer
|
||||
BYTE = 1,
|
||||
/// 8-bit byte that contains a 7-bit ASCII code; the last byte must be zero
|
||||
ASCII = 2,
|
||||
/// 16-bit unsigned integer
|
||||
SHORT = 3,
|
||||
/// 32-bit unsigned integer
|
||||
LONG = 4,
|
||||
/// Fraction stored as two 32-bit unsigned integers
|
||||
RATIONAL = 5,
|
||||
/// 8-bit signed integer
|
||||
SBYTE = 6,
|
||||
/// 8-bit byte that may contain anything, depending on the field
|
||||
UNDEFINED = 7,
|
||||
/// 16-bit signed integer
|
||||
SSHORT = 8,
|
||||
/// 32-bit signed integer
|
||||
SLONG = 9,
|
||||
/// Fraction stored as two 32-bit signed integers
|
||||
SRATIONAL = 10,
|
||||
/// 32-bit IEEE floating point
|
||||
FLOAT = 11,
|
||||
/// 64-bit IEEE floating point
|
||||
DOUBLE = 12,
|
||||
/// 32-bit unsigned integer (offset)
|
||||
IFD = 13,
|
||||
/// BigTIFF 64-bit unsigned integer
|
||||
LONG8 = 16,
|
||||
/// BigTIFF 64-bit signed integer
|
||||
SLONG8 = 17,
|
||||
/// BigTIFF 64-bit unsigned integer (offset)
|
||||
IFD8 = 18,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ macro_rules! test_image_sum {
|
||||
}
|
||||
|
||||
test_image_sum!(test_image_sum_u8, U8, u64);
|
||||
test_image_sum!(test_image_sum_i8, I8, i64);
|
||||
test_image_sum!(test_image_sum_u16, U16, u64);
|
||||
test_image_sum!(test_image_sum_i16, I16, i64);
|
||||
test_image_sum!(test_image_sum_u32, U32, u64);
|
||||
test_image_sum!(test_image_sum_u64, U64, u64);
|
||||
test_image_sum!(test_image_sum_f32, F32, f32);
|
||||
@@ -135,6 +137,26 @@ fn test_rgb_f32() {
|
||||
test_image_sum_f32("gradient-3c-32b-float.tiff", ColorType::RGB(32), 472.8405);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_int8() {
|
||||
test_image_sum_i8("int8.tif", ColorType::Gray(8), 3111)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_int8_rgb() {
|
||||
test_image_sum_i8("int8_rgb.tif", ColorType::RGB(8), -10344)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_int16() {
|
||||
test_image_sum_i16("int16.tif", ColorType::Gray(16), 354396);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_int16_rgb() {
|
||||
test_image_sum_i16("int16_rgb.tif", ColorType::RGB(16), 1063188);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_tags() {
|
||||
// these files have null-terminated strings for their Software tag. One has extra bytes after
|
||||
@@ -193,3 +215,72 @@ fn issue_69() {
|
||||
//let img_res = decoder.read_image();
|
||||
//assert!(img_res.is_ok());
|
||||
//}
|
||||
|
||||
#[test]
|
||||
fn test_tiled_rgb_u8() {
|
||||
test_image_sum_u8("tiled-rgb-u8.tif", ColorType::RGB(8), 39528948);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tiled_rect_rgb_u8() {
|
||||
test_image_sum_u8("tiled-rect-rgb-u8.tif", ColorType::RGB(8), 62081032);
|
||||
}
|
||||
|
||||
/* #[test]
|
||||
fn test_tiled_jpeg_rgb_u8() {
|
||||
test_image_sum_u8("tiled-jpeg-rgb-u8.tif", ColorType::RGB(8), 93031606);
|
||||
} */
|
||||
|
||||
#[test]
|
||||
fn test_tiled_oversize_gray_i8() {
|
||||
test_image_sum_i8("tiled-oversize-gray-i8.tif", ColorType::Gray(8), 1214996);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tiled_cmyk_i8() {
|
||||
test_image_sum_i8("tiled-cmyk-i8.tif", ColorType::CMYK(8), 1759101);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tiled_incremental() {
|
||||
let file = "tiled-rgb-u8.tif";
|
||||
let expected_type = ColorType::RGB(8);
|
||||
let sums = [
|
||||
188760, 195639, 108148, 81986, 665088, 366140, 705317, 423366, 172033, 324455, 244102,
|
||||
81853, 181258, 247971, 129486, 55600, 565625, 422102, 730888, 379271, 232142, 292549,
|
||||
244045, 86866, 188141, 115036, 150785, 84389, 353170, 459325, 719619, 329594, 278663,
|
||||
220474, 243048, 113563, 189152, 109684, 179391, 122188, 279651, 622093, 724682, 302459,
|
||||
268428, 204499, 224255, 124674, 170668, 121868, 192768, 183367, 378029, 585651, 657712,
|
||||
296790, 241444, 197083, 198429, 134869, 182318, 86034, 203655, 182338, 297255, 601284,
|
||||
633813, 242531, 228578, 206441, 193552, 125412, 181527, 165439, 202531, 159538, 268388,
|
||||
565790, 611382, 272967, 236497, 215154, 158881, 90806, 106114, 182342, 191824, 186138,
|
||||
215174, 393193, 701228, 198866, 227944, 193830, 166330, 49008, 55719, 122820, 197316,
|
||||
161969, 203152, 170986, 624427, 188605, 186187, 111064, 115192, 39538, 48626, 163929,
|
||||
144682, 135796, 194141, 154198, 584125, 180255, 153524, 121433, 132641, 35743, 47798,
|
||||
152343, 162874, 167664, 160175, 133038, 659882, 138339, 166470, 124173, 118929, 51317,
|
||||
45267, 155776, 161331, 161006, 130052, 137618, 337291, 106481, 161999, 127343, 87724,
|
||||
59540, 63907, 155677, 140668, 141523, 108061, 168657, 186482, 98599, 147614, 139963, 90444,
|
||||
56602, 92547, 125644, 134212, 126569, 144153, 179800, 174516, 133969, 129399, 117681,
|
||||
83305, 55075, 110737, 115108, 128572, 128911, 130922, 179986, 143288, 145884, 155856,
|
||||
96683, 94057, 56238, 79649, 71651, 70182, 75010, 77009, 98855, 78979, 74341, 83482, 53403,
|
||||
59842, 30305,
|
||||
];
|
||||
|
||||
let path = PathBuf::from(TEST_IMAGE_DIR).join(file);
|
||||
let img_file = File::open(path).expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), expected_type);
|
||||
|
||||
let tiles = decoder.tile_count().unwrap();
|
||||
assert_eq!(tiles as usize, sums.len());
|
||||
|
||||
for tile in 0..tiles {
|
||||
match decoder.read_tile().unwrap() {
|
||||
DecodingResult::U8(res) => {
|
||||
let sum: u64 = res.into_iter().map(<u64>::from).sum();
|
||||
assert_eq!(sum, sums[tile as usize]);
|
||||
}
|
||||
_ => panic!("Wrong bit depth"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
-5
@@ -1,7 +1,7 @@
|
||||
extern crate tiff;
|
||||
|
||||
use tiff::decoder::{ifd, Decoder, DecodingResult};
|
||||
use tiff::encoder::{colortype, SRational, TiffEncoder};
|
||||
use tiff::encoder::{colortype, Ifd, Ifd8, SRational, TiffEncoder};
|
||||
use tiff::tags::Tag;
|
||||
use tiff::ColorType;
|
||||
|
||||
@@ -48,6 +48,92 @@ fn encode_decode() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_decode_big() {
|
||||
let mut image_data = Vec::new();
|
||||
for x in 0..100 {
|
||||
for y in 0..100u8 {
|
||||
let val = x + y;
|
||||
image_data.push(val);
|
||||
image_data.push(val);
|
||||
image_data.push(val);
|
||||
}
|
||||
}
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut tiff = TiffEncoder::new_big(&mut file).unwrap();
|
||||
|
||||
let mut image = tiff.new_image::<colortype::RGB8>(100, 100).unwrap();
|
||||
image
|
||||
.encoder()
|
||||
.write_tag(Tag::Artist, "Image-tiff")
|
||||
.unwrap();
|
||||
image.write_data(&image_data).unwrap();
|
||||
}
|
||||
{
|
||||
file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut decoder = Decoder::new(&mut file).unwrap();
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(8));
|
||||
assert_eq!(decoder.dimensions().unwrap(), (100, 100));
|
||||
assert_eq!(
|
||||
decoder.get_tag(Tag::Artist).unwrap(),
|
||||
ifd::Value::Ascii("Image-tiff".into())
|
||||
);
|
||||
if let DecodingResult::U8(img_res) = decoder.read_image().unwrap() {
|
||||
assert_eq!(image_data, img_res);
|
||||
} else {
|
||||
panic!("Wrong data type");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_ifd() {
|
||||
let mut data = Cursor::new(Vec::new());
|
||||
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut data).unwrap();
|
||||
let mut image_encoder = tiff.new_image::<colortype::Gray8>(1, 1).unwrap();
|
||||
let encoder = image_encoder.encoder();
|
||||
|
||||
// Use the "reusable" tags section as per the TIFF6 spec
|
||||
encoder.write_tag(Tag::Unknown(65000), Ifd(42u32)).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65001), &[Ifd(100u32)][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65002), &[Ifd(1u32), Ifd(2u32), Ifd(3u32)][..])
|
||||
.unwrap();
|
||||
|
||||
encoder.write_tag(Tag::Unknown(65010), Ifd8(43u64)).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65011), &[Ifd8(100u64)][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(
|
||||
Tag::Unknown(65012),
|
||||
&[Ifd8(1u64), Ifd8(2u64), Ifd8(3u64)][..],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Rewind the cursor for reading
|
||||
data.set_position(0);
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut data).unwrap();
|
||||
|
||||
assert_eq!(decoder.assert_tag_u32(65000), 42);
|
||||
assert_eq!(decoder.assert_tag_u32_vec(65000), [42]);
|
||||
assert_eq!(decoder.assert_tag_u32_vec(65001), [100]);
|
||||
assert_eq!(decoder.assert_tag_u32_vec(65002), [1, 2, 3]);
|
||||
|
||||
assert_eq!(decoder.assert_tag_u64(65010), 43);
|
||||
assert_eq!(decoder.assert_tag_u64_vec(65010), [43]);
|
||||
assert_eq!(decoder.assert_tag_u64_vec(65011), [100]);
|
||||
assert_eq!(decoder.assert_tag_u64_vec(65012), [1, 2, 3]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Test that attempting to encode when the input buffer is undersized returns
|
||||
/// an error rather than panicking.
|
||||
@@ -182,6 +268,10 @@ trait AssertDecode {
|
||||
fn assert_tag_u32_vec(&mut self, tag: u16) -> Vec<u32>;
|
||||
fn assert_tag_i32(&mut self, tag: u16) -> i32;
|
||||
fn assert_tag_i32_vec(&mut self, tag: u16) -> Vec<i32>;
|
||||
fn assert_tag_u64(&mut self, tag: u16) -> u64;
|
||||
fn assert_tag_u64_vec(&mut self, tag: u16) -> Vec<u64>;
|
||||
fn assert_tag_i64(&mut self, tag: u16) -> i64;
|
||||
fn assert_tag_i64_vec(&mut self, tag: u16) -> Vec<i64>;
|
||||
}
|
||||
|
||||
impl<R: std::io::Read + std::io::Seek> AssertDecode for Decoder<R> {
|
||||
@@ -203,6 +293,24 @@ impl<R: std::io::Read + std::io::Seek> AssertDecode for Decoder<R> {
|
||||
.into_i32_vec()
|
||||
.unwrap()
|
||||
}
|
||||
fn assert_tag_u64(&mut self, tag: u16) -> u64 {
|
||||
self.get_tag(Tag::Unknown(tag)).unwrap().into_u64().unwrap()
|
||||
}
|
||||
fn assert_tag_u64_vec(&mut self, tag: u16) -> Vec<u64> {
|
||||
self.get_tag(Tag::Unknown(tag))
|
||||
.unwrap()
|
||||
.into_u64_vec()
|
||||
.unwrap()
|
||||
}
|
||||
fn assert_tag_i64(&mut self, tag: u16) -> i64 {
|
||||
self.get_tag(Tag::Unknown(tag)).unwrap().into_i64().unwrap()
|
||||
}
|
||||
fn assert_tag_i64_vec(&mut self, tag: u16) -> Vec<i64> {
|
||||
self.get_tag(Tag::Unknown(tag))
|
||||
.unwrap()
|
||||
.into_i64_vec()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -289,12 +397,20 @@ fn test_signed() {
|
||||
.write_tag(Tag::Unknown(65022), &[-1_i32, 2][..])
|
||||
.unwrap();
|
||||
|
||||
encoder.write_tag(Tag::Unknown(65030), -1_i64).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65030), make_srational(-1))
|
||||
.write_tag(Tag::Unknown(65031), &[-1_i64][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65032), &[-1_i64, 2][..])
|
||||
.unwrap();
|
||||
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65040), make_srational(-1))
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(
|
||||
Tag::Unknown(65031),
|
||||
Tag::Unknown(65041),
|
||||
&[make_srational(-1), make_srational(2)][..],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -321,8 +437,12 @@ fn test_signed() {
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65021), [-1]);
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65022), [-1, 2]);
|
||||
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65030), [-1, 100]);
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65031), [-1_i32, 100, 2, 100]);
|
||||
assert_eq!(decoder.assert_tag_i64(65030), -1);
|
||||
assert_eq!(decoder.assert_tag_i64_vec(65031), [-1]);
|
||||
assert_eq!(decoder.assert_tag_i64_vec(65032), [-1, 2]);
|
||||
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65040), [-1, 100]);
|
||||
assert_eq!(decoder.assert_tag_i32_vec(65041), [-1_i32, 100, 2, 100]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in new issue
Block a user