Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dedc32e9b | ||
|
|
119dec5068 | ||
|
|
ec0477125f | ||
|
|
1c8e98bca5 | ||
|
|
e6985063ac | ||
|
|
42c94ac3d9 | ||
|
|
eadec8f0b9 | ||
|
|
462697e373 | ||
|
|
c537f5cc64 | ||
|
|
8f61196d70 | ||
|
|
298dc8841d | ||
|
|
f92be13f6c | ||
|
|
f9cace84da | ||
|
|
d510a9f4ab | ||
|
|
1fafcccb36 | ||
|
|
8b96793671 | ||
|
|
27ae65160d | ||
|
|
29bb8c2dfe | ||
|
|
c5fcba45a0 | ||
|
|
cbaa9dbc5b | ||
|
|
959254aee9 | ||
|
|
3f14098060 | ||
|
|
57783ba43f | ||
|
|
abd6aee19f | ||
|
|
c72a8d364d | ||
|
|
e5d2e7862c | ||
|
|
6e61de81b6 | ||
|
|
8c4cea5d97 | ||
|
|
0c53e1066a | ||
|
|
f4e985e0bd | ||
|
|
af010edcfd | ||
|
|
f32b3b9d10 | ||
|
|
1f92c562bc | ||
|
|
fca4e1f88a | ||
|
|
ff574b4ca2 | ||
|
|
6f87228458 | ||
|
|
15929f8b8e | ||
|
|
f13492e41d | ||
|
|
1d9944c5c5 | ||
|
|
a14b23473b | ||
|
|
101940335c | ||
|
|
8e1c67ee53 | ||
|
|
7b672998db | ||
|
|
62fee106a7 | ||
|
|
fd789dc420 | ||
|
|
07e8501ad6 | ||
|
|
f70447325e | ||
|
|
b2eb480c44 | ||
|
|
686e9b2648 | ||
|
|
517638a38f | ||
|
|
a6696ab02f | ||
|
|
258edf4a46 | ||
|
|
f88c9f00c3 | ||
|
|
f80f4a06d5 | ||
|
|
cbae42ea94 | ||
|
|
80b8ec5cdb | ||
|
|
ffdeb62b9f | ||
|
|
6aea7b33c1 | ||
|
|
770262cb02 | ||
|
|
1f957029af | ||
|
|
f8d4b57120 | ||
|
|
6f9f2adfbf | ||
|
|
205626bd62 | ||
|
|
ce73d39d57 | ||
|
|
b79128d766 | ||
|
|
c8f384d6a6 | ||
|
|
ce1d4cb289 | ||
|
|
b95e5b8f95 | ||
|
|
bc05e0b7c6 | ||
|
|
3868f78067 | ||
|
|
f6a91065d9 | ||
|
|
ea19f0f686 | ||
|
|
3b85b68ae9 | ||
|
|
30eb8487a6 | ||
|
|
7fb354fe43 |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
language: rust
|
||||
rust:
|
||||
- 1.24.1
|
||||
- 1.34.2
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Version 0.4.0
|
||||
|
||||
* Several enumerations are now non_exhaustive for future extensions.
|
||||
These are `Tag`, `Type`, `Value`, `PhotometricInterpretation`,
|
||||
`CompressionMethod`, `Predictor`.
|
||||
* Enums gained a dedicated method to convert to their TIFF variant value with
|
||||
the specified type. Performing these conversions by casting the discriminant
|
||||
with `as` is not guaranteed to be stable, except where documented explicitly.
|
||||
* Removed the num-derive and num dependencies.
|
||||
* Added support for decoding `deflate` compressed images.
|
||||
* Make the decoder `Limits` customizable by exposing members.
|
||||
* Fixed multi-page TIFF encoding writing incorrect offsets.
|
||||
+2
-6
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tiff"
|
||||
version = "0.3.1"
|
||||
version = "0.4.0"
|
||||
authors = [
|
||||
"ccgn",
|
||||
"bvssvni <bvssvni@gmail.com>",
|
||||
@@ -19,8 +19,4 @@ exclude = ["tests/images/*", "tests/fuzz_images/*"]
|
||||
[dependencies]
|
||||
byteorder = "1.2"
|
||||
lzw = "0.10"
|
||||
num-derive = "0.2"
|
||||
num-traits = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.0"
|
||||
miniz_oxide = "0.3"
|
||||
@@ -4,3 +4,43 @@
|
||||
[](https://crates.io/crates/tiff)
|
||||
|
||||
TIFF decoding and encoding library in pure Rust
|
||||
|
||||
## Supported
|
||||
|
||||
### Features
|
||||
- Baseline spec (other than formats and tags listed below as not supported)
|
||||
- Multipage
|
||||
- Incremental decoding
|
||||
|
||||
### Formats
|
||||
This table lists photometric interpretations and sample formats which are supported for encoding and decoding. The entries are `ColorType` variants for which sample bit depths are supported. Only samples where all bit depths are equal are currently supported. For example, `RGB(8)` means that the bit depth [8, 8, 8] is supported and will be interpreted as an 8 bit per channel RGB color type.
|
||||
|
||||
| `PhotometricInterpretation` | UINT Format | IEEEFP Format |
|
||||
|-|-|-|
|
||||
| `WhiteIsZero` | Gray(8\|16\|32\|64) | |
|
||||
| `BlackIsZero` | Gray(8\|16\|32\|64) | |
|
||||
| `RGB` | RGB(8\|16\|32\|64), RGBA(8\|16\|32\|64) | |
|
||||
| `RGBPalette` | | |
|
||||
| `Mask` | | |
|
||||
| `CMYK` | CMYK(8\|16\|32\|64) | |
|
||||
| `YCbCr` | | |
|
||||
| `CIELab` | | |
|
||||
|
||||
### Compressions
|
||||
|
||||
| | Decoding | Encoding |
|
||||
|-|-|-|
|
||||
| None | ✓ | ✓ |
|
||||
| LZW | ✓ | |
|
||||
| Deflate | ✓ | |
|
||||
| PackBits | ✓ | |
|
||||
|
||||
|
||||
## Not yet supported
|
||||
|
||||
Formats and interpretations not listed above or with empty entries are unsupported.
|
||||
|
||||
- Baseline tags
|
||||
- `ExtraSamples`
|
||||
- Extension tags
|
||||
- BigTIFF
|
||||
+144
-125
@@ -1,104 +1,27 @@
|
||||
//! Function for reading TIFF tags
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::io::{self, Read, Seek};
|
||||
use std::mem;
|
||||
|
||||
use super::stream::{ByteOrder, EndianReader, SmartReader};
|
||||
use tags::{Tag, Type};
|
||||
use {TiffError, TiffFormatError, TiffResult, TiffUnsupportedError};
|
||||
|
||||
use self::Value::{Ascii, List, Rational, Unsigned};
|
||||
|
||||
macro_rules! tags {
|
||||
{$(
|
||||
$tag:ident
|
||||
$val:expr;
|
||||
)*} => {
|
||||
|
||||
/// TIFF tag
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum Tag {
|
||||
$($tag,)*
|
||||
Unknown(u16)
|
||||
}
|
||||
impl Tag {
|
||||
pub fn from_u16(n: u16) -> Tag {
|
||||
$(if n == $val { Tag::$tag } else)* {
|
||||
Tag::Unknown(n)
|
||||
}
|
||||
}
|
||||
pub fn to_u16(&self) -> u16 {
|
||||
match *self {
|
||||
$( Tag::$tag => $val, )*
|
||||
Tag::Unknown(n) => n,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Note: These tags appear in the order they are mentioned in the TIFF reference
|
||||
tags! {
|
||||
// Baseline tags:
|
||||
Artist 315;
|
||||
// grayscale images PhotometricInterpretation 1 or 3
|
||||
BitsPerSample 258;
|
||||
CellLength 265; // TODO add support
|
||||
CellWidth 264; // TODO add support
|
||||
// palette-color images (PhotometricInterpretation 3)
|
||||
ColorMap 320; // TODO add support
|
||||
Compression 259; // TODO add support for 2 and 32773
|
||||
Copyright 33_432;
|
||||
DateTime 306;
|
||||
ExtraSamples 338; // TODO add support
|
||||
FillOrder 266; // TODO add support
|
||||
FreeByteCounts 289; // TODO add support
|
||||
FreeOffsets 288; // TODO add support
|
||||
GrayResponseCurve 291; // TODO add support
|
||||
GrayResponseUnit 290; // TODO add support
|
||||
HostComputer 316;
|
||||
ImageDescription 270;
|
||||
ImageLength 257;
|
||||
ImageWidth 256;
|
||||
Make 271;
|
||||
MaxSampleValue 281; // TODO add support
|
||||
MinSampleValue 280; // TODO add support
|
||||
Model 272;
|
||||
NewSubfileType 254; // TODO add support
|
||||
Orientation 274; // TODO add support
|
||||
PhotometricInterpretation 262;
|
||||
PlanarConfiguration 284;
|
||||
ResolutionUnit 296; // TODO add support
|
||||
RowsPerStrip 278;
|
||||
SamplesPerPixel 277;
|
||||
Software 305;
|
||||
StripByteCounts 279;
|
||||
StripOffsets 273;
|
||||
SubfileType 255; // TODO add support
|
||||
Threshholding 263; // TODO add support
|
||||
XResolution 282;
|
||||
YResolution 283;
|
||||
// Advanced tags
|
||||
Predictor 317;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, FromPrimitive)]
|
||||
pub enum Type {
|
||||
BYTE = 1,
|
||||
ASCII = 2,
|
||||
SHORT = 3,
|
||||
LONG = 4,
|
||||
RATIONAL = 5,
|
||||
}
|
||||
use self::Value::{Ascii, List, Rational, SRational, Signed, Unsigned};
|
||||
|
||||
#[allow(unused_qualifications)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Value {
|
||||
//Signed(i32),
|
||||
Signed(i32),
|
||||
Unsigned(u32),
|
||||
List(Vec<Value>),
|
||||
Rational(u32, u32),
|
||||
SRational(i32, i32),
|
||||
Ascii(String),
|
||||
#[doc(hidden)] // Do not match against this.
|
||||
__NonExhaustive,
|
||||
}
|
||||
|
||||
impl Value {
|
||||
@@ -110,6 +33,16 @@ impl Value {
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_i32(self) -> TiffResult<i32> {
|
||||
match self {
|
||||
Signed(val) => Ok(val),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::SignedIntegerExpected(val),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_u32_vec(self) -> TiffResult<Vec<u32>> {
|
||||
match self {
|
||||
List(vec) => {
|
||||
@@ -121,7 +54,33 @@ impl Value {
|
||||
}
|
||||
Unsigned(val) => Ok(vec![val]),
|
||||
Rational(numerator, denominator) => Ok(vec![numerator, denominator]),
|
||||
Ascii(val) => Ok(val.chars().map(|x| x as u32).collect()),
|
||||
Ascii(val) => Ok(val.chars().map(u32::from).collect()),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::UnsignedIntegerExpected(val),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_i32_vec(self) -> TiffResult<Vec<i32>> {
|
||||
match self {
|
||||
List(vec) => {
|
||||
let mut new_vec = Vec::with_capacity(vec.len());
|
||||
for v in vec {
|
||||
match v {
|
||||
SRational(numerator, denominator) => {
|
||||
new_vec.push(numerator);
|
||||
new_vec.push(denominator);
|
||||
}
|
||||
_ => new_vec.push(v.into_i32()?),
|
||||
}
|
||||
}
|
||||
Ok(new_vec)
|
||||
}
|
||||
Signed(val) => Ok(vec![val]),
|
||||
SRational(numerator, denominator) => Ok(vec![numerator, denominator]),
|
||||
val => Err(TiffError::FormatError(
|
||||
TiffFormatError::SignedIntegerExpected(val),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,7 +125,21 @@ impl Entry {
|
||||
// TODO check if this could give wrong results
|
||||
// at a different endianess of file/computer.
|
||||
(Type::BYTE, 1) => Ok(Unsigned(u32::from(self.offset[0]))),
|
||||
(Type::BYTE, 2) => offset_to_bytes(2, self),
|
||||
(Type::BYTE, 3) => offset_to_bytes(3, self),
|
||||
(Type::BYTE, 4) => offset_to_bytes(4, self),
|
||||
(Type::BYTE, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Unsigned(u32::from(decoder.read_byte()?)))
|
||||
}),
|
||||
(Type::SBYTE, 1) => Ok(Signed(i32::from(self.offset[0] as i8))),
|
||||
(Type::SBYTE, 2) => offset_to_sbytes(2, self),
|
||||
(Type::SBYTE, 3) => offset_to_sbytes(3, self),
|
||||
(Type::SBYTE, 4) => offset_to_sbytes(4, self),
|
||||
(Type::SBYTE, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Signed(i32::from(decoder.read_byte()? as i8)))
|
||||
}),
|
||||
(Type::SHORT, 1) => Ok(Unsigned(u32::from(self.r(bo).read_u16()?))),
|
||||
(Type::SSHORT, 1) => Ok(Signed(i32::from(self.r(bo).read_i16()?))),
|
||||
(Type::SHORT, 2) => {
|
||||
let mut r = self.r(bo);
|
||||
Ok(List(vec![
|
||||
@@ -174,54 +147,52 @@ impl Entry {
|
||||
Unsigned(u32::from(r.read_u16()?)),
|
||||
]))
|
||||
}
|
||||
(Type::SHORT, n) => {
|
||||
if n as usize > limits.decoding_buffer_size / mem::size_of::<Value>() {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
let mut v = Vec::with_capacity(n as usize);
|
||||
try!(decoder.goto_offset(try!(self.r(bo).read_u32())));
|
||||
for _ in 0..n {
|
||||
v.push(Unsigned(u32::from(decoder.read_short()?)))
|
||||
}
|
||||
Ok(List(v))
|
||||
}
|
||||
(Type::LONG, 1) => Ok(Unsigned(try!(self.r(bo).read_u32()))),
|
||||
(Type::LONG, n) => {
|
||||
if n as usize > limits.decoding_buffer_size / mem::size_of::<Value>() {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
let mut v = Vec::with_capacity(n as usize);
|
||||
try!(decoder.goto_offset(try!(self.r(bo).read_u32())));
|
||||
for _ in 0..n {
|
||||
v.push(Unsigned(try!(decoder.read_long())))
|
||||
}
|
||||
Ok(List(v))
|
||||
(Type::SSHORT, 2) => {
|
||||
let mut r = self.r(bo);
|
||||
Ok(List(vec![
|
||||
Signed(i32::from(r.read_i16()?)),
|
||||
Signed(i32::from(r.read_i16()?)),
|
||||
]))
|
||||
}
|
||||
(Type::SHORT, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Unsigned(u32::from(decoder.read_short()?)))
|
||||
}),
|
||||
(Type::SSHORT, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Signed(i32::from(decoder.read_sshort()?)))
|
||||
}),
|
||||
(Type::LONG, 1) => Ok(Unsigned(self.r(bo).read_u32()?)),
|
||||
(Type::SLONG, 1) => Ok(Signed(self.r(bo).read_i32()?)),
|
||||
(Type::LONG, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Unsigned(decoder.read_long()?))
|
||||
}),
|
||||
(Type::SLONG, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Signed(decoder.read_slong()?))
|
||||
}),
|
||||
(Type::RATIONAL, 1) => {
|
||||
try!(decoder.goto_offset(try!(self.r(bo).read_u32())));
|
||||
let numerator = try!(decoder.read_long());
|
||||
let denominator = try!(decoder.read_long());
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
let numerator = decoder.read_long()?;
|
||||
let denominator = decoder.read_long()?;
|
||||
Ok(Rational(numerator, denominator))
|
||||
}
|
||||
(Type::RATIONAL, n) => {
|
||||
if n as usize > limits.decoding_buffer_size / mem::size_of::<Value>() {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
let mut v = Vec::with_capacity(n as usize);
|
||||
try!(decoder.goto_offset(try!(self.r(bo).read_u32())));
|
||||
for _ in 0..n {
|
||||
let numerator = try!(decoder.read_long());
|
||||
let denominator = try!(decoder.read_long());
|
||||
v.push(Rational(numerator, denominator))
|
||||
}
|
||||
Ok(List(v))
|
||||
(Type::SRATIONAL, 1) => {
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
let numerator = decoder.read_slong()?;
|
||||
let denominator = decoder.read_slong()?;
|
||||
Ok(SRational(numerator, denominator))
|
||||
}
|
||||
(Type::RATIONAL, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(Rational(decoder.read_long()?, decoder.read_long()?))
|
||||
}),
|
||||
(Type::SRATIONAL, n) => self.decode_offset(n, bo, limits, decoder, |decoder| {
|
||||
Ok(SRational(decoder.read_slong()?, decoder.read_slong()?))
|
||||
}),
|
||||
(Type::ASCII, n) => {
|
||||
if n as usize > limits.decoding_buffer_size {
|
||||
let n = usize::try_from(n)?;
|
||||
if n > limits.decoding_buffer_size {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
try!(decoder.goto_offset(try!(self.r(bo).read_u32())));
|
||||
let string = try!(decoder.read_string(n as usize));
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
let string = decoder.read_string(n)?;
|
||||
Ok(Ascii(string))
|
||||
}
|
||||
_ => Err(TiffError::UnsupportedError(
|
||||
@@ -229,6 +200,54 @@ impl Entry {
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_offset<R, F>(
|
||||
&self,
|
||||
value_count: u32,
|
||||
bo: ByteOrder,
|
||||
limits: &super::Limits,
|
||||
decoder: &mut super::Decoder<R>,
|
||||
decode_fn: F,
|
||||
) -> TiffResult<Value>
|
||||
where
|
||||
R: Read + Seek,
|
||||
F: Fn(&mut super::Decoder<R>) -> TiffResult<Value>,
|
||||
{
|
||||
let value_count = usize::try_from(value_count)?;
|
||||
if value_count > limits.decoding_buffer_size / mem::size_of::<Value>() {
|
||||
return Err(TiffError::LimitsExceeded);
|
||||
}
|
||||
|
||||
let mut v = Vec::with_capacity(value_count);
|
||||
decoder.goto_offset(self.r(bo).read_u32()?)?;
|
||||
for _ in 0..value_count {
|
||||
v.push(decode_fn(decoder)?)
|
||||
}
|
||||
Ok(List(v))
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts a list of BYTE tags stored in an offset
|
||||
#[inline]
|
||||
fn offset_to_bytes(n: usize, entry: &Entry) -> TiffResult<Value> {
|
||||
Ok(List(
|
||||
entry.offset[0..n]
|
||||
.iter()
|
||||
.map(|&e| Unsigned(u32::from(e)))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Extracts a list of SBYTE tags stored in an offset
|
||||
#[inline]
|
||||
fn offset_to_sbytes(n: usize, entry: &Entry) -> TiffResult<Value> {
|
||||
Ok(List(
|
||||
entry.offset[0..n]
|
||||
.iter()
|
||||
.map(|&e| Signed(i32::from(e as i8)))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Type representing an Image File Directory
|
||||
|
||||
+280
-200
@@ -1,13 +1,16 @@
|
||||
use num_traits::{FromPrimitive, Num};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Read, Seek};
|
||||
use std::cmp;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::io::{self, Read, Seek};
|
||||
|
||||
use {ColorType, TiffError, TiffFormatError, TiffResult, TiffUnsupportedError};
|
||||
|
||||
use self::ifd::Directory;
|
||||
use tags::{CompressionMethod, PhotometricInterpretation, Predictor, Tag, Type};
|
||||
|
||||
use self::stream::{ByteOrder, EndianReader, LZWReader, PackBitsReader, SmartReader};
|
||||
use self::stream::{
|
||||
ByteOrder, DeflateReader, EndianReader, LZWReader, PackBitsReader, SmartReader,
|
||||
};
|
||||
|
||||
pub mod ifd;
|
||||
mod stream;
|
||||
@@ -19,6 +22,10 @@ pub enum DecodingResult {
|
||||
U8(Vec<u8>),
|
||||
/// A vector of unsigned words
|
||||
U16(Vec<u16>),
|
||||
/// A vector of 32 bit unsigned ints
|
||||
U32(Vec<u32>),
|
||||
/// A vector of 64 bit unsigned ints
|
||||
U64(Vec<u64>),
|
||||
}
|
||||
|
||||
impl DecodingResult {
|
||||
@@ -38,10 +45,28 @@ impl DecodingResult {
|
||||
}
|
||||
}
|
||||
|
||||
fn new_u32(size: usize, limits: &Limits) -> TiffResult<DecodingResult> {
|
||||
if size > limits.decoding_buffer_size / 4 {
|
||||
Err(TiffError::LimitsExceeded)
|
||||
} else {
|
||||
Ok(DecodingResult::U32(vec![0; size]))
|
||||
}
|
||||
}
|
||||
|
||||
fn new_u64(size: usize, limits: &Limits) -> TiffResult<DecodingResult> {
|
||||
if size > limits.decoding_buffer_size / 8 {
|
||||
Err(TiffError::LimitsExceeded)
|
||||
} else {
|
||||
Ok(DecodingResult::U64(vec![0; size]))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_buffer(&mut self, start: usize) -> DecodingBuffer {
|
||||
match *self {
|
||||
DecodingResult::U8(ref mut buf) => DecodingBuffer::U8(&mut buf[start..]),
|
||||
DecodingResult::U16(ref mut buf) => DecodingBuffer::U16(&mut buf[start..]),
|
||||
DecodingResult::U32(ref mut buf) => DecodingBuffer::U32(&mut buf[start..]),
|
||||
DecodingResult::U64(ref mut buf) => DecodingBuffer::U64(&mut buf[start..]),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +77,10 @@ pub enum DecodingBuffer<'a> {
|
||||
U8(&'a mut [u8]),
|
||||
/// A slice of unsigned words
|
||||
U16(&'a mut [u16]),
|
||||
/// A slice of 32 bit unsigned ints
|
||||
U32(&'a mut [u32]),
|
||||
/// A slice of 64 bit unsigned ints
|
||||
U64(&'a mut [u64]),
|
||||
}
|
||||
|
||||
impl<'a> DecodingBuffer<'a> {
|
||||
@@ -59,6 +88,8 @@ impl<'a> DecodingBuffer<'a> {
|
||||
match *self {
|
||||
DecodingBuffer::U8(ref buf) => buf.len(),
|
||||
DecodingBuffer::U16(ref buf) => buf.len(),
|
||||
DecodingBuffer::U32(ref buf) => buf.len(),
|
||||
DecodingBuffer::U64(ref buf) => buf.len(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +97,8 @@ impl<'a> DecodingBuffer<'a> {
|
||||
match *self {
|
||||
DecodingBuffer::U8(_) => 1,
|
||||
DecodingBuffer::U16(_) => 2,
|
||||
DecodingBuffer::U32(_) => 4,
|
||||
DecodingBuffer::U64(_) => 8,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,45 +109,12 @@ impl<'a> DecodingBuffer<'a> {
|
||||
match *self {
|
||||
DecodingBuffer::U8(ref mut buf) => DecodingBuffer::U8(buf),
|
||||
DecodingBuffer::U16(ref mut buf) => DecodingBuffer::U16(buf),
|
||||
DecodingBuffer::U32(ref mut buf) => DecodingBuffer::U32(buf),
|
||||
DecodingBuffer::U64(ref mut buf) => DecodingBuffer::U64(buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, FromPrimitive)]
|
||||
pub enum PhotometricInterpretation {
|
||||
WhiteIsZero = 0,
|
||||
BlackIsZero = 1,
|
||||
RGB = 2,
|
||||
RGBPalette = 3,
|
||||
TransparencyMask = 4,
|
||||
CMYK = 5,
|
||||
YCbCr = 6,
|
||||
CIELab = 8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, FromPrimitive)]
|
||||
pub enum CompressionMethod {
|
||||
None = 1,
|
||||
Huffman = 2,
|
||||
Fax3 = 3,
|
||||
Fax4 = 4,
|
||||
LZW = 5,
|
||||
JPEG = 6,
|
||||
PackBits = 0x8005,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, FromPrimitive)]
|
||||
pub enum PlanarConfiguration {
|
||||
Chunky = 1,
|
||||
Planar = 2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, FromPrimitive)]
|
||||
enum Predictor {
|
||||
None = 1,
|
||||
Horizontal = 2,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StripDecodeState {
|
||||
strip_index: usize,
|
||||
@@ -129,10 +129,14 @@ pub struct Limits {
|
||||
/// 256MiB. If the entire image is decoded at once, then this will
|
||||
/// be the maximum size of the image. If it is decoded one strip at a
|
||||
/// time, this will be the maximum size of a strip.
|
||||
decoding_buffer_size: usize,
|
||||
pub decoding_buffer_size: usize,
|
||||
/// The maximum size of any ifd value in bytes, the default is
|
||||
/// 1MiB.
|
||||
ifd_value_size: usize,
|
||||
pub ifd_value_size: usize,
|
||||
/// The purpose of this is to prevent all the fields of the struct from
|
||||
/// being public, as this would make adding new fields a major version
|
||||
/// bump.
|
||||
_non_exhaustive: (),
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
@@ -140,6 +144,7 @@ impl Default for Limits {
|
||||
Limits {
|
||||
decoding_buffer_size: 256 * 1024 * 1024,
|
||||
ifd_value_size: 1024 * 1024,
|
||||
_non_exhaustive: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,12 +187,24 @@ impl Wrapping for u16 {
|
||||
}
|
||||
}
|
||||
|
||||
fn rev_hpredict_nsamp<T>(image: &mut [T], size: (u32, u32), samples: usize)
|
||||
impl Wrapping for u32 {
|
||||
fn wrapping_add(&self, other: Self) -> Self {
|
||||
u32::wrapping_add(*self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Wrapping for u64 {
|
||||
fn wrapping_add(&self, other: Self) -> Self {
|
||||
u64::wrapping_add(*self, other)
|
||||
}
|
||||
}
|
||||
|
||||
fn rev_hpredict_nsamp<T>(image: &mut [T], size: (u32, u32), samples: usize) -> TiffResult<()>
|
||||
where
|
||||
T: Num + Copy + Wrapping,
|
||||
T: Copy + Wrapping,
|
||||
{
|
||||
let width = size.0 as usize;
|
||||
let height = size.1 as usize;
|
||||
let width = usize::try_from(size.0)?;
|
||||
let height = usize::try_from(size.1)?;
|
||||
for row in 0..height {
|
||||
for col in samples..width * samples {
|
||||
let prev_pixel = image[(row * width * samples + col - samples)];
|
||||
@@ -195,13 +212,21 @@ where
|
||||
*pixel = pixel.wrapping_add(prev_pixel);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rev_hpredict(image: DecodingBuffer, size: (u32, u32), color_type: ColorType) -> TiffResult<()> {
|
||||
let samples = match color_type {
|
||||
ColorType::Gray(8) | ColorType::Gray(16) => 1,
|
||||
ColorType::RGB(8) | ColorType::RGB(16) => 3,
|
||||
ColorType::RGBA(8) | ColorType::RGBA(16) | ColorType::CMYK(8) => 4,
|
||||
ColorType::Gray(8) | ColorType::Gray(16) | ColorType::Gray(32) | ColorType::Gray(64) => 1,
|
||||
ColorType::RGB(8) | ColorType::RGB(16) | ColorType::RGB(32) | ColorType::RGB(64) => 3,
|
||||
ColorType::RGBA(8)
|
||||
| ColorType::RGBA(16)
|
||||
| ColorType::RGBA(32)
|
||||
| ColorType::RGBA(64)
|
||||
| ColorType::CMYK(8)
|
||||
| ColorType::CMYK(16)
|
||||
| ColorType::CMYK(32)
|
||||
| ColorType::CMYK(64) => 4,
|
||||
_ => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::HorizontalPredictor(color_type),
|
||||
@@ -210,10 +235,16 @@ fn rev_hpredict(image: DecodingBuffer, size: (u32, u32), color_type: ColorType)
|
||||
};
|
||||
match image {
|
||||
DecodingBuffer::U8(buf) => {
|
||||
rev_hpredict_nsamp(buf, size, samples);
|
||||
rev_hpredict_nsamp(buf, size, samples)?;
|
||||
}
|
||||
DecodingBuffer::U16(buf) => {
|
||||
rev_hpredict_nsamp(buf, size, samples);
|
||||
rev_hpredict_nsamp(buf, size, samples)?;
|
||||
}
|
||||
DecodingBuffer::U32(buf) => {
|
||||
rev_hpredict_nsamp(buf, size, samples)?;
|
||||
}
|
||||
DecodingBuffer::U64(buf) => {
|
||||
rev_hpredict_nsamp(buf, size, samples)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -250,22 +281,25 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
pub fn colortype(&mut self) -> TiffResult<ColorType> {
|
||||
match self.photometric_interpretation {
|
||||
// TODO: catch also [ 8, 8, 8, _] this does not work due to a bug in rust atm
|
||||
PhotometricInterpretation::RGB if self.bits_per_sample == [8, 8, 8, 8] => {
|
||||
Ok(ColorType::RGBA(8))
|
||||
}
|
||||
PhotometricInterpretation::RGB if self.bits_per_sample == [8, 8, 8] => {
|
||||
Ok(ColorType::RGB(8))
|
||||
}
|
||||
PhotometricInterpretation::RGB if self.bits_per_sample == [16, 16, 16, 16] => {
|
||||
Ok(ColorType::RGBA(16))
|
||||
}
|
||||
PhotometricInterpretation::RGB if self.bits_per_sample == [16, 16, 16] => {
|
||||
Ok(ColorType::RGB(16))
|
||||
}
|
||||
PhotometricInterpretation::CMYK if self.bits_per_sample == [8, 8, 8, 8] => {
|
||||
Ok(ColorType::CMYK(8))
|
||||
}
|
||||
PhotometricInterpretation::RGB => match self.bits_per_sample[..] {
|
||||
[r, g, b] if [r, r] == [g, b] => Ok(ColorType::RGB(r)),
|
||||
[r, g, b, a] if [r, r, r] == [g, b, a] => Ok(ColorType::RGBA(r)),
|
||||
_ => Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::InterpretationWithBits(
|
||||
self.photometric_interpretation,
|
||||
self.bits_per_sample.clone(),
|
||||
),
|
||||
)),
|
||||
},
|
||||
PhotometricInterpretation::CMYK => match self.bits_per_sample[..] {
|
||||
[c, m, y, k] if [c, c, c] == [m, y, k] => Ok(ColorType::CMYK(c)),
|
||||
_ => Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::InterpretationWithBits(
|
||||
self.photometric_interpretation,
|
||||
self.bits_per_sample.clone(),
|
||||
),
|
||||
)),
|
||||
},
|
||||
PhotometricInterpretation::BlackIsZero | PhotometricInterpretation::WhiteIsZero
|
||||
if self.bits_per_sample.len() == 1 =>
|
||||
{
|
||||
@@ -284,7 +318,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
fn read_header(&mut self) -> TiffResult<()> {
|
||||
let mut endianess = Vec::with_capacity(2);
|
||||
try!(self.reader.by_ref().take(2).read_to_end(&mut endianess));
|
||||
self.reader.by_ref().take(2).read_to_end(&mut endianess)?;
|
||||
match &*endianess {
|
||||
b"II" => {
|
||||
self.byte_order = ByteOrder::LittleEndian;
|
||||
@@ -300,12 +334,12 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
))
|
||||
}
|
||||
}
|
||||
if try!(self.read_short()) != 42 {
|
||||
if self.read_short()? != 42 {
|
||||
return Err(TiffError::FormatError(
|
||||
TiffFormatError::TiffSignatureInvalid,
|
||||
));
|
||||
}
|
||||
self.next_ifd = match try!(self.read_long()) {
|
||||
self.next_ifd = match self.read_long()? {
|
||||
0 => None,
|
||||
n => Some(n),
|
||||
};
|
||||
@@ -314,7 +348,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
/// Initializes the decoder.
|
||||
pub fn init(mut self) -> TiffResult<Decoder<R>> {
|
||||
try!(self.read_header());
|
||||
self.read_header()?;
|
||||
self.next_image()?;
|
||||
Ok(self)
|
||||
}
|
||||
@@ -323,49 +357,30 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
/// If there is no further image in the TIFF file a format error is returned.
|
||||
/// To determine whether there are more images call `TIFFDecoder::more_images` instead.
|
||||
pub fn next_image(&mut self) -> TiffResult<()> {
|
||||
self.ifd = Some(try!(self.read_ifd()));
|
||||
self.width = try!(self.get_tag_u32(ifd::Tag::ImageWidth));
|
||||
self.height = try!(self.get_tag_u32(ifd::Tag::ImageLength));
|
||||
self.ifd = Some(self.read_ifd()?);
|
||||
self.width = self.get_tag_u32(Tag::ImageWidth)?;
|
||||
self.height = self.get_tag_u32(Tag::ImageLength)?;
|
||||
self.strip_decoder = None;
|
||||
self.photometric_interpretation = match FromPrimitive::from_u32(try!(
|
||||
self.get_tag_u32(ifd::Tag::PhotometricInterpretation)
|
||||
)) {
|
||||
Some(val) => val,
|
||||
None => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnknownInterpretation,
|
||||
))
|
||||
|
||||
self.photometric_interpretation = self
|
||||
.find_tag_unsigned(Tag::PhotometricInterpretation)?
|
||||
.and_then(PhotometricInterpretation::from_u16)
|
||||
.ok_or(TiffUnsupportedError::UnknownInterpretation)?;
|
||||
|
||||
if let Some(val) = self.find_tag_unsigned(Tag::Compression)? {
|
||||
self.compression_method = CompressionMethod::from_u16(val)
|
||||
.ok_or(TiffUnsupportedError::UnknownCompressionMethod)?;
|
||||
}
|
||||
};
|
||||
if let Some(val) = try!(self.find_tag_u32(ifd::Tag::Compression)) {
|
||||
match FromPrimitive::from_u32(val) {
|
||||
Some(method) => self.compression_method = method,
|
||||
None => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnknownCompressionMethod,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(val) = try!(self.find_tag_u32(ifd::Tag::SamplesPerPixel)) {
|
||||
self.samples = val as u8
|
||||
if let Some(val) = self.find_tag_unsigned(Tag::SamplesPerPixel)? {
|
||||
self.samples = val;
|
||||
}
|
||||
match self.samples {
|
||||
1 => {
|
||||
if let Some(val) = try!(self.find_tag_u32(ifd::Tag::BitsPerSample)) {
|
||||
self.bits_per_sample = vec![val as u8]
|
||||
1 | 3 | 4 => {
|
||||
if let Some(val) = self.find_tag_unsigned_vec(Tag::BitsPerSample)? {
|
||||
self.bits_per_sample = val;
|
||||
}
|
||||
}
|
||||
3 | 4 => {
|
||||
if let Some(val) = try!(self.find_tag_u32_vec(ifd::Tag::BitsPerSample)) {
|
||||
self.bits_per_sample = val.iter().map(|&v| v as u8).collect()
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnsupportedSampleDepth(self.samples),
|
||||
))
|
||||
}
|
||||
_ => return Err(TiffUnsupportedError::UnsupportedSampleDepth(self.samples).into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -380,18 +395,38 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
self.byte_order
|
||||
}
|
||||
|
||||
/// Reads a TIFF byte value
|
||||
#[inline]
|
||||
pub fn read_byte(&mut self) -> Result<u8, io::Error> {
|
||||
let mut buf = [0; 1];
|
||||
self.reader.read_exact(&mut buf)?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Reads a TIFF short value
|
||||
#[inline]
|
||||
pub fn read_short(&mut self) -> Result<u16, io::Error> {
|
||||
self.reader.read_u16()
|
||||
}
|
||||
|
||||
/// Reads a TIFF sshort value
|
||||
#[inline]
|
||||
pub fn read_sshort(&mut self) -> Result<i16, io::Error> {
|
||||
self.reader.read_i16()
|
||||
}
|
||||
|
||||
/// Reads a TIFF long value
|
||||
#[inline]
|
||||
pub fn read_long(&mut self) -> Result<u32, io::Error> {
|
||||
self.reader.read_u32()
|
||||
}
|
||||
|
||||
/// Reads a TIFF slong value
|
||||
#[inline]
|
||||
pub fn read_slong(&mut self) -> Result<i32, io::Error> {
|
||||
self.reader.read_i32()
|
||||
}
|
||||
|
||||
/// Reads a string
|
||||
#[inline]
|
||||
pub fn read_string(&mut self, length: usize) -> TiffResult<String> {
|
||||
@@ -406,7 +441,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
#[inline]
|
||||
pub fn read_offset(&mut self) -> Result<[u8; 4], io::Error> {
|
||||
let mut val = [0; 4];
|
||||
try!(self.reader.read_exact(&mut val));
|
||||
self.reader.read_exact(&mut val)?;
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
@@ -425,14 +460,14 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
// Type 2 bytes
|
||||
// Count 4 bytes
|
||||
// Value 4 bytes either a pointer the value itself
|
||||
fn read_entry(&mut self) -> TiffResult<Option<(ifd::Tag, ifd::Entry)>> {
|
||||
let tag = ifd::Tag::from_u16(try!(self.read_short()));
|
||||
let type_: ifd::Type = match FromPrimitive::from_u16(try!(self.read_short())) {
|
||||
fn read_entry(&mut self) -> TiffResult<Option<(Tag, ifd::Entry)>> {
|
||||
let tag = Tag::from_u16_exhaustive(self.read_short()?);
|
||||
let type_ = match Type::from_u16(self.read_short()?) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
// Unknown type. Skip this entry according to spec.
|
||||
try!(self.read_long());
|
||||
try!(self.read_long());
|
||||
self.read_long()?;
|
||||
self.read_long()?;
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
@@ -440,8 +475,8 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
tag,
|
||||
ifd::Entry::new(
|
||||
type_,
|
||||
try!(self.read_long()), // count
|
||||
try!(self.read_offset()), // offset
|
||||
self.read_long()?, // count
|
||||
self.read_offset()?, // offset
|
||||
),
|
||||
)))
|
||||
}
|
||||
@@ -455,16 +490,16 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
TiffFormatError::ImageFileDirectoryNotFound,
|
||||
))
|
||||
}
|
||||
Some(offset) => try!(self.goto_offset(offset)),
|
||||
Some(offset) => self.goto_offset(offset)?,
|
||||
}
|
||||
for _ in 0..try!(self.read_short()) {
|
||||
let (tag, entry) = match try!(self.read_entry()) {
|
||||
for _ in 0..self.read_short()? {
|
||||
let (tag, entry) = match self.read_entry()? {
|
||||
Some(val) => val,
|
||||
None => continue, // Unknown data type in tag, skip
|
||||
};
|
||||
dir.insert(tag, entry);
|
||||
}
|
||||
self.next_ifd = match try!(self.read_long()) {
|
||||
self.next_ifd = match self.read_long()? {
|
||||
0 => None,
|
||||
n => Some(n),
|
||||
};
|
||||
@@ -473,7 +508,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
/// Tries to retrieve a tag.
|
||||
/// Return `Ok(None)` if the tag is not present.
|
||||
pub fn find_tag(&mut self, tag: ifd::Tag) -> TiffResult<Option<ifd::Value>> {
|
||||
pub fn find_tag(&mut self, tag: Tag) -> TiffResult<Option<ifd::Value>> {
|
||||
let entry = match self.ifd.as_ref().unwrap().get(&tag) {
|
||||
None => return Ok(None),
|
||||
Some(entry) => entry.clone(),
|
||||
@@ -481,29 +516,50 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
let limits = self.limits.clone();
|
||||
|
||||
Ok(Some(try!(entry.val(&limits, self))))
|
||||
Ok(Some(entry.val(&limits, self)?))
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag and convert it to the desired type.
|
||||
pub fn find_tag_u32(&mut self, tag: ifd::Tag) -> TiffResult<Option<u32>> {
|
||||
match self.find_tag(tag)? {
|
||||
Some(val) => val.into_u32().map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
/// Tries to retrieve a tag and convert it to the desired unsigned type.
|
||||
pub fn find_tag_unsigned<T: TryFrom<u32>>(&mut self, tag: Tag) -> TiffResult<Option<T>> {
|
||||
self.find_tag(tag)?
|
||||
.map(|v| v.into_u32())
|
||||
.transpose()?
|
||||
.map(|value| {
|
||||
T::try_from(value).map_err(|_| TiffFormatError::InvalidTagValueType(tag).into())
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag and convert it to the desired type.
|
||||
pub fn find_tag_u32_vec(&mut self, tag: ifd::Tag) -> TiffResult<Option<Vec<u32>>> {
|
||||
match self.find_tag(tag)? {
|
||||
Some(val) => val.into_u32_vec().map(Some),
|
||||
None => Ok(None),
|
||||
/// Tries to retrieve a vector of all a tag's values and convert them to
|
||||
/// the desired unsigned type.
|
||||
pub fn find_tag_unsigned_vec<T: TryFrom<u32>>(
|
||||
&mut self,
|
||||
tag: Tag,
|
||||
) -> TiffResult<Option<Vec<T>>> {
|
||||
self.find_tag(tag)?
|
||||
.map(|v| v.into_u32_vec())
|
||||
.transpose()?
|
||||
.map(|v| {
|
||||
v.into_iter()
|
||||
.map(|u| {
|
||||
T::try_from(u).map_err(|_| TiffFormatError::InvalidTagValueType(tag).into())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag and convert it to the desired unsigned type.
|
||||
/// Returns an error if the tag is not present.
|
||||
pub fn get_tag_unsigned<T: TryFrom<u32>>(&mut self, tag: Tag) -> TiffResult<T> {
|
||||
self.find_tag_unsigned(tag)?
|
||||
.ok_or_else(|| TiffFormatError::RequiredTagNotFound(tag).into())
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag.
|
||||
/// Returns an error if the tag is not present
|
||||
pub fn get_tag(&mut self, tag: ifd::Tag) -> TiffResult<ifd::Value> {
|
||||
match try!(self.find_tag(tag)) {
|
||||
pub fn get_tag(&mut self, tag: Tag) -> TiffResult<ifd::Value> {
|
||||
match self.find_tag(tag)? {
|
||||
Some(val) => Ok(val),
|
||||
None => Err(TiffError::FormatError(
|
||||
TiffFormatError::RequiredTagNotFound(tag),
|
||||
@@ -512,12 +568,12 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag and convert it to the desired type.
|
||||
pub fn get_tag_u32(&mut self, tag: ifd::Tag) -> TiffResult<u32> {
|
||||
pub fn get_tag_u32(&mut self, tag: Tag) -> TiffResult<u32> {
|
||||
self.get_tag(tag)?.into_u32()
|
||||
}
|
||||
|
||||
/// Tries to retrieve a tag and convert it to the desired type.
|
||||
pub fn get_tag_u32_vec(&mut self, tag: ifd::Tag) -> TiffResult<Vec<u32>> {
|
||||
pub fn get_tag_u32_vec(&mut self, tag: Tag) -> TiffResult<Vec<u32>> {
|
||||
self.get_tag(tag)?.into_u32_vec()
|
||||
}
|
||||
|
||||
@@ -530,31 +586,33 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
length: u32,
|
||||
max_uncompressed_length: usize,
|
||||
) -> TiffResult<usize> {
|
||||
let color_type = try!(self.colortype());
|
||||
try!(self.goto_offset(offset));
|
||||
let color_type = self.colortype()?;
|
||||
self.goto_offset(offset)?;
|
||||
let (bytes, mut reader): (usize, Box<EndianReader>) = match self.compression_method {
|
||||
CompressionMethod::None => {
|
||||
let order = self.reader.byte_order;
|
||||
(
|
||||
length as usize,
|
||||
usize::try_from(length)?,
|
||||
Box::new(SmartReader::wrap(&mut self.reader, order)),
|
||||
)
|
||||
}
|
||||
CompressionMethod::LZW => {
|
||||
let (bytes, reader) = try!(LZWReader::new(
|
||||
let (bytes, reader) = LZWReader::new(
|
||||
&mut self.reader,
|
||||
length as usize,
|
||||
max_uncompressed_length
|
||||
));
|
||||
usize::try_from(length)?,
|
||||
max_uncompressed_length,
|
||||
)?;
|
||||
(bytes, Box::new(reader))
|
||||
}
|
||||
CompressionMethod::PackBits => {
|
||||
let order = self.reader.byte_order;
|
||||
let (bytes, reader) = try!(PackBitsReader::new(
|
||||
&mut self.reader,
|
||||
order,
|
||||
length as usize
|
||||
));
|
||||
let (bytes, reader) =
|
||||
PackBitsReader::new(&mut self.reader, order, usize::try_from(length)?)?;
|
||||
(bytes, Box::new(reader))
|
||||
}
|
||||
CompressionMethod::OldDeflate => {
|
||||
let (bytes, reader) =
|
||||
DeflateReader::new(&mut self.reader, max_uncompressed_length)?;
|
||||
(bytes, Box::new(reader))
|
||||
}
|
||||
method => {
|
||||
@@ -574,16 +632,47 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
(ColorType::RGB(8), DecodingBuffer::U8(ref mut buffer))
|
||||
| (ColorType::RGBA(8), DecodingBuffer::U8(ref mut buffer))
|
||||
| (ColorType::CMYK(8), DecodingBuffer::U8(ref mut buffer)) => {
|
||||
try!(reader.read_exact(&mut buffer[..bytes]));
|
||||
reader.read_exact(&mut buffer[..bytes])?;
|
||||
bytes
|
||||
}
|
||||
(ColorType::RGBA(16), DecodingBuffer::U16(ref mut buffer))
|
||||
| (ColorType::RGB(16), DecodingBuffer::U16(ref mut buffer)) => {
|
||||
try!(reader.read_u16_into(&mut buffer[..bytes / 2]));
|
||||
| (ColorType::RGB(16), DecodingBuffer::U16(ref mut buffer))
|
||||
| (ColorType::CMYK(16), DecodingBuffer::U16(ref mut buffer)) => {
|
||||
reader.read_u16_into(&mut buffer[..bytes / 2])?;
|
||||
bytes / 2
|
||||
}
|
||||
(ColorType::RGBA(32), DecodingBuffer::U32(ref mut buffer))
|
||||
| (ColorType::RGB(32), DecodingBuffer::U32(ref mut buffer))
|
||||
| (ColorType::CMYK(32), DecodingBuffer::U32(ref mut buffer)) => {
|
||||
reader.read_u32_into(&mut buffer[..bytes / 4])?;
|
||||
bytes / 4
|
||||
}
|
||||
(ColorType::RGBA(64), DecodingBuffer::U64(ref mut buffer))
|
||||
| (ColorType::RGB(64), DecodingBuffer::U64(ref mut buffer))
|
||||
| (ColorType::CMYK(64), DecodingBuffer::U64(ref mut buffer)) => {
|
||||
reader.read_u64_into(&mut buffer[..bytes / 8])?;
|
||||
bytes / 8
|
||||
}
|
||||
(ColorType::Gray(64), DecodingBuffer::U64(ref mut buffer)) => {
|
||||
reader.read_u64_into(&mut buffer[..bytes / 8])?;
|
||||
if self.photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
|
||||
for datum in buffer[..bytes / 8].iter_mut() {
|
||||
*datum = 0xffff_ffff_ffff_ffff - *datum
|
||||
}
|
||||
}
|
||||
bytes / 8
|
||||
}
|
||||
(ColorType::Gray(32), DecodingBuffer::U32(ref mut buffer)) => {
|
||||
reader.read_u32_into(&mut buffer[..bytes / 4])?;
|
||||
if self.photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
|
||||
for datum in buffer[..bytes / 4].iter_mut() {
|
||||
*datum = 0xffff_ffff - *datum
|
||||
}
|
||||
}
|
||||
bytes / 4
|
||||
}
|
||||
(ColorType::Gray(16), DecodingBuffer::U16(ref mut buffer)) => {
|
||||
try!(reader.read_u16_into(&mut buffer[..bytes / 2]));
|
||||
reader.read_u16_into(&mut buffer[..bytes / 2])?;
|
||||
if self.photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
|
||||
for datum in buffer[..bytes / 2].iter_mut() {
|
||||
*datum = 0xffff - *datum
|
||||
@@ -592,7 +681,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
bytes / 2
|
||||
}
|
||||
(ColorType::Gray(n), DecodingBuffer::U8(ref mut buffer)) if n <= 8 => {
|
||||
try!(reader.read_exact(&mut buffer[..bytes]));
|
||||
reader.read_exact(&mut buffer[..bytes])?;
|
||||
if self.photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
|
||||
for byte in buffer[..bytes].iter_mut() {
|
||||
*byte = 0xff - *byte
|
||||
@@ -610,9 +699,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
/// Number of strips in image
|
||||
pub fn strip_count(&mut self) -> TiffResult<u32> {
|
||||
let rows_per_strip = self
|
||||
.get_tag_u32(ifd::Tag::RowsPerStrip)
|
||||
.unwrap_or(self.height);
|
||||
let rows_per_strip = self.get_tag_u32(Tag::RowsPerStrip).unwrap_or(self.height);
|
||||
|
||||
if rows_per_strip == 0 {
|
||||
return Ok(0);
|
||||
@@ -623,8 +710,8 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
fn initialize_strip_decoder(&mut self) -> TiffResult<()> {
|
||||
if self.strip_decoder.is_none() {
|
||||
let strip_offsets = self.get_tag_u32_vec(ifd::Tag::StripOffsets)?;
|
||||
let strip_bytes = self.get_tag_u32_vec(ifd::Tag::StripByteCounts)?;
|
||||
let strip_offsets = self.get_tag_u32_vec(Tag::StripOffsets)?;
|
||||
let strip_bytes = self.get_tag_u32_vec(Tag::StripByteCounts)?;
|
||||
|
||||
self.strip_decoder = Some(StripDecodeState {
|
||||
strip_index: 0,
|
||||
@@ -658,18 +745,19 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
TiffFormatError::InconsistentSizesEncountered,
|
||||
))?;
|
||||
|
||||
let rows_per_strip = self
|
||||
.get_tag_u32(ifd::Tag::RowsPerStrip)
|
||||
.unwrap_or(self.height) as usize;
|
||||
let rows_per_strip =
|
||||
usize::try_from(self.get_tag_u32(Tag::RowsPerStrip).unwrap_or(self.height))?;
|
||||
|
||||
let strip_height = cmp::min(
|
||||
rows_per_strip,
|
||||
self.height as usize - index * rows_per_strip,
|
||||
usize::try_from(self.height)? - index * rows_per_strip,
|
||||
);
|
||||
|
||||
let buffer_size = self.width as usize * strip_height * self.bits_per_sample.len();
|
||||
let buffer_size = usize::try_from(self.width)? * strip_height * self.bits_per_sample.len();
|
||||
|
||||
if buffer.len() < buffer_size || byte_count as usize / buffer.byte_len() > buffer_size {
|
||||
if buffer.len() < buffer_size
|
||||
|| usize::try_from(byte_count)? / buffer.byte_len() > buffer_size
|
||||
{
|
||||
return Err(TiffError::FormatError(
|
||||
TiffFormatError::InconsistentSizesEncountered,
|
||||
));
|
||||
@@ -679,7 +767,7 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
|
||||
self.strip_decoder.as_mut().unwrap().strip_index += 1;
|
||||
|
||||
if index as u32 == self.strip_count()? {
|
||||
if u32::try_from(index)? == self.strip_count()? {
|
||||
self.strip_decoder = None;
|
||||
}
|
||||
|
||||
@@ -688,13 +776,13 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
TiffFormatError::InconsistentSizesEncountered,
|
||||
));
|
||||
}
|
||||
if let Ok(predictor) = self.get_tag_u32(ifd::Tag::Predictor) {
|
||||
match FromPrimitive::from_u32(predictor) {
|
||||
if let Ok(predictor) = self.get_tag_unsigned(Tag::Predictor) {
|
||||
match Predictor::from_u16(predictor) {
|
||||
Some(Predictor::None) => (),
|
||||
Some(Predictor::Horizontal) => {
|
||||
rev_hpredict(
|
||||
buffer.copy(),
|
||||
(self.width, strip_height as u32),
|
||||
(self.width, u32::try_from(strip_height)?),
|
||||
self.colortype()?,
|
||||
)?;
|
||||
}
|
||||
@@ -703,36 +791,40 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
predictor,
|
||||
)))
|
||||
}
|
||||
Some(Predictor::__NonExhaustive) => unreachable!(),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn result_buffer(&self, height: usize) -> TiffResult<DecodingResult> {
|
||||
let buffer_size = usize::try_from(self.width)? * height * self.bits_per_sample.len();
|
||||
|
||||
match self.bits_per_sample.iter().cloned().max().unwrap_or(8) {
|
||||
n if n <= 8 => DecodingResult::new_u8(buffer_size, &self.limits),
|
||||
n if n <= 16 => DecodingResult::new_u16(buffer_size, &self.limits),
|
||||
n if n <= 32 => DecodingResult::new_u32(buffer_size, &self.limits),
|
||||
n if n <= 64 => DecodingResult::new_u64(buffer_size, &self.limits),
|
||||
n => Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnsupportedBitsPerChannel(n),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a single strip from the image and return it as a Vector
|
||||
pub fn read_strip(&mut self) -> TiffResult<DecodingResult> {
|
||||
self.initialize_strip_decoder()?;
|
||||
let index = self.strip_decoder.as_ref().unwrap().strip_index;
|
||||
|
||||
let rows_per_strip = self
|
||||
.get_tag_u32(ifd::Tag::RowsPerStrip)
|
||||
.unwrap_or(self.height) as usize;
|
||||
let rows_per_strip =
|
||||
usize::try_from(self.get_tag_u32(Tag::RowsPerStrip).unwrap_or(self.height))?;
|
||||
|
||||
let strip_height = cmp::min(
|
||||
rows_per_strip,
|
||||
self.height as usize - index * rows_per_strip,
|
||||
usize::try_from(self.height)? - index * rows_per_strip,
|
||||
);
|
||||
|
||||
let buffer_size = self.width as usize * strip_height * self.bits_per_sample.iter().count();
|
||||
|
||||
let mut result = match self.bits_per_sample.iter().cloned().max().unwrap_or(8) {
|
||||
n if n <= 8 => DecodingResult::new_u8(buffer_size, &self.limits)?,
|
||||
n if n <= 16 => DecodingResult::new_u16(buffer_size, &self.limits)?,
|
||||
n => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnsupportedBitsPerChannel(n),
|
||||
))
|
||||
}
|
||||
};
|
||||
let mut result = self.result_buffer(strip_height)?;
|
||||
|
||||
self.read_strip_to_buffer(result.as_buffer(0))?;
|
||||
|
||||
@@ -742,27 +834,15 @@ impl<R: Read + Seek> Decoder<R> {
|
||||
/// Decodes the entire image and return it as a Vector
|
||||
pub fn read_image(&mut self) -> TiffResult<DecodingResult> {
|
||||
self.initialize_strip_decoder()?;
|
||||
let rows_per_strip = self
|
||||
.get_tag_u32(ifd::Tag::RowsPerStrip)
|
||||
.unwrap_or(self.height) as usize;
|
||||
let rows_per_strip =
|
||||
usize::try_from(self.get_tag_u32(Tag::RowsPerStrip).unwrap_or(self.height))?;
|
||||
|
||||
let samples_per_strip =
|
||||
self.width as usize * rows_per_strip * self.bits_per_sample.iter().count();
|
||||
usize::try_from(self.width)? * rows_per_strip * self.bits_per_sample.len();
|
||||
|
||||
let buffer_size =
|
||||
self.width as usize * self.height as usize * self.bits_per_sample.iter().count();
|
||||
let mut result = self.result_buffer(usize::try_from(self.height)?)?;
|
||||
|
||||
let mut result = match self.bits_per_sample.iter().cloned().max().unwrap_or(8) {
|
||||
n if n <= 8 => DecodingResult::new_u8(buffer_size, &self.limits)?,
|
||||
n if n <= 16 => DecodingResult::new_u16(buffer_size, &self.limits)?,
|
||||
n => {
|
||||
return Err(TiffError::UnsupportedError(
|
||||
TiffUnsupportedError::UnsupportedBitsPerChannel(n),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
for i in 0..self.strip_count()? as usize {
|
||||
for i in 0..usize::try_from(self.strip_count()?)? {
|
||||
self.read_strip_to_buffer(result.as_buffer(samples_per_strip * i))?;
|
||||
}
|
||||
|
||||
|
||||
+104
-5
@@ -1,7 +1,9 @@
|
||||
//! All IO functionality needed for TIFF decoding
|
||||
|
||||
use crate::error::{TiffError, TiffResult};
|
||||
use byteorder::{BigEndian, LittleEndian, ReadBytesExt};
|
||||
use lzw;
|
||||
use miniz_oxide::inflate;
|
||||
use std::io::{self, Read, Seek};
|
||||
|
||||
/// Byte order of the TIFF file.
|
||||
@@ -39,6 +41,15 @@ pub trait EndianReader: Read {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads an i16
|
||||
#[inline(always)]
|
||||
fn read_i16(&mut self) -> Result<i16, io::Error> {
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => <Self as ReadBytesExt>::read_i16::<LittleEndian>(self),
|
||||
ByteOrder::BigEndian => <Self as ReadBytesExt>::read_i16::<BigEndian>(self),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads an u32
|
||||
#[inline(always)]
|
||||
fn read_u32(&mut self) -> Result<u32, io::Error> {
|
||||
@@ -47,6 +58,94 @@ pub trait EndianReader: Read {
|
||||
ByteOrder::BigEndian => <Self as ReadBytesExt>::read_u32::<BigEndian>(self),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_u32_into(&mut self, buffer: &mut [u32]) -> Result<(), io::Error> {
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
<Self as ReadBytesExt>::read_u32_into::<LittleEndian>(self, buffer)
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
<Self as ReadBytesExt>::read_u32_into::<BigEndian>(self, buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads an u64
|
||||
#[inline(always)]
|
||||
fn read_u64(&mut self) -> Result<u64, io::Error> {
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => <Self as ReadBytesExt>::read_u64::<LittleEndian>(self),
|
||||
ByteOrder::BigEndian => <Self as ReadBytesExt>::read_u64::<BigEndian>(self),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_u64_into(&mut self, buffer: &mut [u64]) -> Result<(), io::Error> {
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => {
|
||||
<Self as ReadBytesExt>::read_u64_into::<LittleEndian>(self, buffer)
|
||||
}
|
||||
ByteOrder::BigEndian => {
|
||||
<Self as ReadBytesExt>::read_u64_into::<BigEndian>(self, buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads an i32
|
||||
#[inline(always)]
|
||||
fn read_i32(&mut self) -> Result<i32, io::Error> {
|
||||
match self.byte_order() {
|
||||
ByteOrder::LittleEndian => <Self as ReadBytesExt>::read_i32::<LittleEndian>(self),
|
||||
ByteOrder::BigEndian => <Self as ReadBytesExt>::read_i32::<BigEndian>(self),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader that decompresses LZW streams
|
||||
@@ -67,12 +166,12 @@ impl LZWReader {
|
||||
{
|
||||
let order = reader.byte_order;
|
||||
let mut compressed = vec![0; compressed_length as usize];
|
||||
try!(reader.read_exact(&mut compressed[..]));
|
||||
reader.read_exact(&mut compressed[..])?;
|
||||
let mut uncompressed = Vec::with_capacity(max_uncompressed_length);
|
||||
let mut decoder = lzw::DecoderEarlyChange::new(lzw::MsbReader::new(), 8);
|
||||
let mut bytes_read = 0;
|
||||
while bytes_read < compressed_length && uncompressed.len() < max_uncompressed_length {
|
||||
let (len, bytes) = try!(decoder.decode_bytes(&compressed[bytes_read..]));
|
||||
let (len, bytes) = decoder.decode_bytes(&compressed[bytes_read..])?;
|
||||
bytes_read += len;
|
||||
uncompressed.extend_from_slice(bytes);
|
||||
}
|
||||
@@ -137,7 +236,7 @@ impl PackBitsReader {
|
||||
fn read_packbits_run<R: Read + Seek>(reader: &mut R, buffer: &mut Vec<u8>) -> io::Result<usize> {
|
||||
let mut header: [u8; 1] = [0];
|
||||
|
||||
let bytes = try!(reader.read(&mut header));
|
||||
let bytes = reader.read(&mut header)?;
|
||||
|
||||
match bytes {
|
||||
0 => Ok(0),
|
||||
@@ -145,7 +244,7 @@ fn read_packbits_run<R: Read + Seek>(reader: &mut R, buffer: &mut Vec<u8>) -> io
|
||||
-128 => Ok(1),
|
||||
h if h >= -127 && h <= -1 => {
|
||||
let new_len = buffer.len() + (1 - h as isize) as usize;
|
||||
try!(reader.read_exact(&mut header));
|
||||
reader.read_exact(&mut header)?;
|
||||
buffer.resize(new_len, header[0]);
|
||||
Ok(2)
|
||||
}
|
||||
@@ -153,7 +252,7 @@ fn read_packbits_run<R: Read + Seek>(reader: &mut R, buffer: &mut Vec<u8>) -> io
|
||||
let num_vals = h as usize + 1;
|
||||
let start = buffer.len();
|
||||
buffer.resize(start + num_vals, 0);
|
||||
try!(reader.read_exact(&mut buffer[start..]));
|
||||
reader.read_exact(&mut buffer[start..])?;
|
||||
Ok(num_vals + 1)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use decoder::PhotometricInterpretation;
|
||||
use tags::PhotometricInterpretation;
|
||||
|
||||
/// Trait for different colortypes that can be encoded.
|
||||
pub trait ColorType {
|
||||
@@ -24,6 +24,20 @@ impl ColorType for Gray16 {
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[16];
|
||||
}
|
||||
|
||||
pub struct Gray32;
|
||||
impl ColorType for Gray32 {
|
||||
type Inner = u32;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::BlackIsZero;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[32];
|
||||
}
|
||||
|
||||
pub struct Gray64;
|
||||
impl ColorType for Gray64 {
|
||||
type Inner = u64;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::BlackIsZero;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[64];
|
||||
}
|
||||
|
||||
pub struct RGB8;
|
||||
impl ColorType for RGB8 {
|
||||
type Inner = u8;
|
||||
@@ -38,6 +52,20 @@ impl ColorType for RGB16 {
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[16, 16, 16];
|
||||
}
|
||||
|
||||
pub struct RGB32;
|
||||
impl ColorType for RGB32 {
|
||||
type Inner = u32;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::RGB;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[32, 32, 32];
|
||||
}
|
||||
|
||||
pub struct RGB64;
|
||||
impl ColorType for RGB64 {
|
||||
type Inner = u64;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::RGB;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[64, 64, 64];
|
||||
}
|
||||
|
||||
pub struct RGBA8;
|
||||
impl ColorType for RGBA8 {
|
||||
type Inner = u8;
|
||||
@@ -52,9 +80,44 @@ impl ColorType for RGBA16 {
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[16, 16, 16, 16];
|
||||
}
|
||||
|
||||
pub struct RGBA32;
|
||||
impl ColorType for RGBA32 {
|
||||
type Inner = u16;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::RGB;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[32, 32, 32, 32];
|
||||
}
|
||||
|
||||
pub struct RGBA64;
|
||||
impl ColorType for RGBA64 {
|
||||
type Inner = u16;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::RGB;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[64, 64, 64, 64];
|
||||
}
|
||||
|
||||
pub struct CMYK8;
|
||||
impl ColorType for CMYK8 {
|
||||
type Inner = u8;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::CMYK;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[8, 8, 8, 8];
|
||||
}
|
||||
|
||||
pub struct CMYK16;
|
||||
impl ColorType for CMYK16 {
|
||||
type Inner = u16;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::CMYK;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[16, 16, 16, 16];
|
||||
}
|
||||
|
||||
pub struct CMYK32;
|
||||
impl ColorType for CMYK32 {
|
||||
type Inner = u32;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::CMYK;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[32, 32, 32, 32];
|
||||
}
|
||||
|
||||
pub struct CMYK64;
|
||||
impl ColorType for CMYK64 {
|
||||
type Inner = u64;
|
||||
const TIFF_VALUE: PhotometricInterpretation = PhotometricInterpretation::CMYK;
|
||||
const BITS_PER_SAMPLE: &'static [u16] = &[64, 64, 64, 64];
|
||||
}
|
||||
+245
-60
@@ -1,9 +1,11 @@
|
||||
use byteorder::NativeEndian;
|
||||
use std::collections::BTreeMap;
|
||||
use std::convert::TryFrom;
|
||||
use std::io::{Seek, Write};
|
||||
use std::mem;
|
||||
|
||||
use decoder::ifd::{self, Tag};
|
||||
use error::{TiffError, TiffFormatError, TiffResult};
|
||||
use tags::{self, ResolutionUnit, Tag, Type};
|
||||
|
||||
pub mod colortype;
|
||||
mod writer;
|
||||
@@ -18,17 +20,16 @@ pub struct Rational {
|
||||
pub d: u32,
|
||||
}
|
||||
|
||||
/// Type to represent resolution units
|
||||
pub enum ResolutionUnit {
|
||||
None = 1,
|
||||
Inch = 2,
|
||||
Centimeter = 3,
|
||||
/// 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: ifd::Type;
|
||||
const FIELD_TYPE: Type;
|
||||
fn count(&self) -> u32;
|
||||
fn bytes(&self) -> u32 {
|
||||
self.count() * Self::BYTE_LEN
|
||||
@@ -38,7 +39,7 @@ pub trait TiffValue {
|
||||
|
||||
impl TiffValue for [u8] {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::BYTE;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
@@ -50,9 +51,25 @@ impl TiffValue for [u8] {
|
||||
}
|
||||
}
|
||||
|
||||
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<()> {
|
||||
// We write using nativeedian so this should be safe
|
||||
let slice = unsafe { ::std::slice::from_raw_parts(self.as_ptr() as *const u8, self.len()) };
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u16] {
|
||||
const BYTE_LEN: u32 = 2;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::SHORT;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
@@ -67,9 +84,30 @@ impl TiffValue for [u16] {
|
||||
}
|
||||
}
|
||||
|
||||
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<()> {
|
||||
// We write using nativeedian so this should be safe
|
||||
let slice = unsafe {
|
||||
::std::slice::from_raw_parts(
|
||||
self.as_ptr() as *const u8,
|
||||
self.len() * Self::BYTE_LEN as usize,
|
||||
)
|
||||
};
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [u32] {
|
||||
const BYTE_LEN: u32 = 4;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::LONG;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32
|
||||
@@ -84,9 +122,63 @@ impl TiffValue for [u32] {
|
||||
}
|
||||
}
|
||||
|
||||
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<()> {
|
||||
// We write using nativeedian so this should be safe
|
||||
let slice = unsafe {
|
||||
::std::slice::from_raw_parts(
|
||||
self.as_ptr() as *const u8,
|
||||
self.len() * Self::BYTE_LEN as usize,
|
||||
)
|
||||
};
|
||||
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<()> {
|
||||
// We write using nativeedian so this sould be safe
|
||||
let slice =
|
||||
unsafe { ::std::slice::from_raw_parts(self.as_ptr() as *const u8, self.len() * 8) };
|
||||
writer.write_bytes(slice)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TiffValue for [Rational] {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::RATIONAL;
|
||||
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
|
||||
@@ -102,7 +194,7 @@ impl TiffValue for [Rational] {
|
||||
|
||||
impl TiffValue for u8 {
|
||||
const BYTE_LEN: u32 = 1;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::BYTE;
|
||||
const FIELD_TYPE: Type = Type::BYTE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
@@ -114,9 +206,23 @@ impl TiffValue for u8 {
|
||||
}
|
||||
}
|
||||
|
||||
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: ifd::Type = ifd::Type::SHORT;
|
||||
const FIELD_TYPE: Type = Type::SHORT;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
@@ -128,9 +234,23 @@ impl TiffValue for u16 {
|
||||
}
|
||||
}
|
||||
|
||||
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: ifd::Type = ifd::Type::LONG;
|
||||
const FIELD_TYPE: Type = Type::LONG;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
@@ -142,9 +262,37 @@ impl TiffValue for u32 {
|
||||
}
|
||||
}
|
||||
|
||||
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 Rational {
|
||||
const BYTE_LEN: u32 = 8;
|
||||
const FIELD_TYPE: ifd::Type = ifd::Type::RATIONAL;
|
||||
const FIELD_TYPE: Type = Type::RATIONAL;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
1
|
||||
@@ -157,9 +305,24 @@ impl TiffValue for Rational {
|
||||
}
|
||||
}
|
||||
|
||||
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: ifd::Type = ifd::Type::ASCII;
|
||||
const FIELD_TYPE: Type = Type::ASCII;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.len() as u32 + 1
|
||||
@@ -178,7 +341,7 @@ impl TiffValue for str {
|
||||
|
||||
impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
|
||||
const BYTE_LEN: u32 = T::BYTE_LEN;
|
||||
const FIELD_TYPE: ifd::Type = T::FIELD_TYPE;
|
||||
const FIELD_TYPE: Type = T::FIELD_TYPE;
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
(*self).count()
|
||||
@@ -198,10 +361,9 @@ impl<'a, T: TiffValue + ?Sized> TiffValue for &'a T {
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// # extern crate tempfile;
|
||||
/// # extern crate tiff;
|
||||
/// # fn main() {
|
||||
/// # let mut file = tempfile::tempfile().unwrap();
|
||||
/// # let mut file = std::io::Cursor::new(Vec::new());
|
||||
/// # let image_data = vec![0; 100*100*3];
|
||||
/// use tiff::encoder::*;
|
||||
///
|
||||
@@ -221,6 +383,8 @@ impl<W: Write + Seek> TiffEncoder<W> {
|
||||
};
|
||||
|
||||
NativeEndian::write_header(&mut encoder.writer)?;
|
||||
// blank the IFD offset location
|
||||
encoder.writer.write_u32(0)?;
|
||||
|
||||
Ok(encoder)
|
||||
}
|
||||
@@ -250,14 +414,20 @@ impl<W: Write + Seek> TiffEncoder<W> {
|
||||
where
|
||||
[C::Inner]: TiffValue,
|
||||
{
|
||||
let num_pix = (width as usize).checked_mul(height as usize)
|
||||
.ok_or_else(|| ::std::io::Error::new(
|
||||
let num_pix = usize::try_from(width)?
|
||||
.checked_mul(usize::try_from(height)?)
|
||||
.ok_or_else(|| {
|
||||
::std::io::Error::new(
|
||||
::std::io::ErrorKind::InvalidInput,
|
||||
"Image width * height exceeds usize"))?;
|
||||
"Image width * height exceeds usize",
|
||||
)
|
||||
})?;
|
||||
if data.len() < num_pix {
|
||||
return Err(::std::io::Error::new(
|
||||
::std::io::ErrorKind::InvalidData,
|
||||
"Input data slice is undersized for provided dimensions").into());
|
||||
"Input data slice is undersized for provided dimensions",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let encoder = DirectoryEncoder::new(&mut self.writer)?;
|
||||
@@ -265,7 +435,7 @@ impl<W: Write + Seek> TiffEncoder<W> {
|
||||
|
||||
let mut idx = 0;
|
||||
while image.next_strip_sample_count() > 0 {
|
||||
let sample_count = image.next_strip_sample_count() as usize;
|
||||
let sample_count = usize::try_from(image.next_strip_sample_count())?;
|
||||
image.write_strip(&data[idx..idx + sample_count])?;
|
||||
idx += sample_count;
|
||||
}
|
||||
@@ -287,9 +457,9 @@ pub struct DirectoryEncoder<'a, W: 'a + Write + Seek> {
|
||||
|
||||
impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
fn new(writer: &'a mut TiffWriter<W>) -> TiffResult<DirectoryEncoder<'a, W>> {
|
||||
// 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();
|
||||
writer.write_u32(0)?;
|
||||
Ok(DirectoryEncoder {
|
||||
writer,
|
||||
dropped: false,
|
||||
@@ -299,16 +469,20 @@ 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) {
|
||||
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(len as usize);
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(len)?);
|
||||
{
|
||||
let mut writer = TiffWriter::new(&mut bytes);
|
||||
value.write(&mut writer).unwrap();
|
||||
value.write(&mut writer)?;
|
||||
}
|
||||
|
||||
self.ifd
|
||||
.insert(tag.to_u16(), (<T>::FIELD_TYPE as u16, value.count(), bytes));
|
||||
self.ifd.insert(
|
||||
tag.to_u16(),
|
||||
(<T>::FIELD_TYPE.to_u16(), value.count(), bytes),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_directory(&mut self) -> TiffResult<u64> {
|
||||
@@ -319,7 +493,7 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
self.writer.write_bytes(bytes)?;
|
||||
*bytes = vec![0, 0, 0, 0];
|
||||
let mut writer = TiffWriter::new(bytes as &mut [u8]);
|
||||
writer.write_u32(offset as u32)?;
|
||||
writer.write_u32(u32::try_from(offset)?)?;
|
||||
} else {
|
||||
while bytes.len() < 4 {
|
||||
bytes.push(0);
|
||||
@@ -329,7 +503,7 @@ impl<'a, W: 'a + Write + Seek> DirectoryEncoder<'a, W> {
|
||||
|
||||
let offset = self.writer.offset();
|
||||
|
||||
self.writer.write_u16(self.ifd.len() as u16)?;
|
||||
self.writer.write_u16(u16::try_from(self.ifd.len())?)?;
|
||||
for (tag, &(ref field_type, ref count, ref offset)) in self.ifd.iter() {
|
||||
self.writer.write_u16(*tag)?;
|
||||
self.writer.write_u16(*field_type)?;
|
||||
@@ -354,7 +528,7 @@ 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(ifd_pointer as u32)?;
|
||||
self.writer.write_u32(u32::try_from(ifd_pointer)?)?;
|
||||
self.writer.goto_offset(curr_pos)?;
|
||||
self.writer.write_u32(0)?;
|
||||
|
||||
@@ -384,10 +558,9 @@ impl<'a, W: Write + Seek> Drop for DirectoryEncoder<'a, W> {
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// # extern crate tempfile;
|
||||
/// # extern crate tiff;
|
||||
/// # fn main() {
|
||||
/// # let mut file = tempfile::tempfile().unwrap();
|
||||
/// # let mut file = std::io::Cursor::new(Vec::new());
|
||||
/// # let image_data = vec![0; 100*100*3];
|
||||
/// use tiff::encoder::*;
|
||||
///
|
||||
@@ -422,7 +595,7 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> TiffResult<ImageEncoder<'a, W, T>> {
|
||||
let row_samples = u64::from(width) * <T>::BITS_PER_SAMPLE.len() as u64;
|
||||
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);
|
||||
|
||||
// As per tiff spec each strip should be about 8k long
|
||||
@@ -430,19 +603,22 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
|
||||
let strip_count = (u64::from(height) + rows_per_strip - 1) / rows_per_strip;
|
||||
|
||||
encoder.write_tag(Tag::ImageWidth, width);
|
||||
encoder.write_tag(Tag::ImageLength, height);
|
||||
encoder.write_tag(Tag::Compression, 1u16);
|
||||
encoder.write_tag(Tag::ImageWidth, width)?;
|
||||
encoder.write_tag(Tag::ImageLength, height)?;
|
||||
encoder.write_tag(Tag::Compression, tags::CompressionMethod::None.to_u16())?;
|
||||
|
||||
encoder.write_tag(Tag::BitsPerSample, <T>::BITS_PER_SAMPLE);
|
||||
encoder.write_tag(Tag::PhotometricInterpretation, <T>::TIFF_VALUE as u16);
|
||||
encoder.write_tag(Tag::BitsPerSample, <T>::BITS_PER_SAMPLE)?;
|
||||
encoder.write_tag(Tag::PhotometricInterpretation, <T>::TIFF_VALUE.to_u16())?;
|
||||
|
||||
encoder.write_tag(Tag::RowsPerStrip, rows_per_strip as u32);
|
||||
encoder.write_tag(Tag::RowsPerStrip, u32::try_from(rows_per_strip)?)?;
|
||||
|
||||
encoder.write_tag(Tag::SamplesPerPixel, <T>::BITS_PER_SAMPLE.len() as u16);
|
||||
encoder.write_tag(Tag::XResolution, Rational { n: 1, d: 1 });
|
||||
encoder.write_tag(Tag::YResolution, Rational { n: 1, d: 1 });
|
||||
encoder.write_tag(Tag::ResolutionUnit, 1u16);
|
||||
encoder.write_tag(
|
||||
Tag::SamplesPerPixel,
|
||||
u16::try_from(<T>::BITS_PER_SAMPLE.len())?,
|
||||
)?;
|
||||
encoder.write_tag(Tag::XResolution, Rational { n: 1, d: 1 })?;
|
||||
encoder.write_tag(Tag::YResolution, Rational { n: 1, d: 1 })?;
|
||||
encoder.write_tag(Tag::ResolutionUnit, ResolutionUnit::None.to_u16())?;
|
||||
|
||||
Ok(ImageEncoder {
|
||||
encoder,
|
||||
@@ -464,7 +640,8 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let start_row = ::std::cmp::min(u64::from(self.height), self.strip_idx * self.rows_per_strip);
|
||||
let start_row =
|
||||
::std::cmp::min(u64::from(self.height), self.strip_idx * self.rows_per_strip);
|
||||
let end_row = ::std::cmp::min(
|
||||
u64::from(self.height),
|
||||
(self.strip_idx + 1) * self.rows_per_strip,
|
||||
@@ -480,15 +657,17 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
{
|
||||
// TODO: Compression
|
||||
let samples = self.next_strip_sample_count();
|
||||
if value.len() as u64 != samples {
|
||||
if u64::try_from(value.len())? != samples {
|
||||
return Err(::std::io::Error::new(
|
||||
::std::io::ErrorKind::InvalidData,
|
||||
"Slice is wrong size for strip").into());
|
||||
"Slice is wrong size for strip",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let offset = self.encoder.write_data(value)?;
|
||||
self.strip_offsets.push(offset as u32);
|
||||
self.strip_byte_count.push(value.bytes() as u32);
|
||||
self.strip_offsets.push(u32::try_from(offset)?);
|
||||
self.strip_byte_count.push(value.bytes());
|
||||
|
||||
self.strip_idx += 1;
|
||||
Ok(())
|
||||
@@ -496,31 +675,37 @@ impl<'a, W: 'a + Write + Seek, T: ColorType> ImageEncoder<'a, W, T> {
|
||||
|
||||
/// Set image resolution
|
||||
pub fn resolution(&mut self, unit: ResolutionUnit, value: Rational) {
|
||||
self.encoder.write_tag(Tag::ResolutionUnit, unit as u16);
|
||||
self.encoder.write_tag(Tag::XResolution, value.clone());
|
||||
self.encoder.write_tag(Tag::YResolution, value);
|
||||
self.encoder
|
||||
.write_tag(Tag::ResolutionUnit, unit.to_u16())
|
||||
.unwrap();
|
||||
self.encoder
|
||||
.write_tag(Tag::XResolution, value.clone())
|
||||
.unwrap();
|
||||
self.encoder.write_tag(Tag::YResolution, value).unwrap();
|
||||
}
|
||||
|
||||
/// Set image resolution unit
|
||||
pub fn resolution_unit(&mut self, unit: ResolutionUnit) {
|
||||
self.encoder.write_tag(Tag::ResolutionUnit, unit as u16);
|
||||
self.encoder
|
||||
.write_tag(Tag::ResolutionUnit, unit.to_u16())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Set image x-resolution
|
||||
pub fn x_resolution(&mut self, value: Rational) {
|
||||
self.encoder.write_tag(Tag::XResolution, value);
|
||||
self.encoder.write_tag(Tag::XResolution, value).unwrap();
|
||||
}
|
||||
|
||||
/// Set image y-resolution
|
||||
pub fn y_resolution(&mut self, value: Rational) {
|
||||
self.encoder.write_tag(Tag::YResolution, value);
|
||||
self.encoder.write_tag(Tag::YResolution, value).unwrap();
|
||||
}
|
||||
|
||||
fn finish_internal(&mut self) -> TiffResult<()> {
|
||||
self.encoder
|
||||
.write_tag(Tag::StripOffsets, &*self.strip_offsets);
|
||||
.write_tag(Tag::StripOffsets, &*self.strip_offsets)?;
|
||||
self.encoder
|
||||
.write_tag(Tag::StripByteCounts, &*self.strip_byte_count);
|
||||
.write_tag(Tag::StripByteCounts, &*self.strip_byte_count)?;
|
||||
self.dropped = true;
|
||||
|
||||
self.encoder.finish_internal()
|
||||
|
||||
+22
-1
@@ -1,5 +1,5 @@
|
||||
use error::TiffResult;
|
||||
use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian, WriteBytesExt};
|
||||
use error::TiffResult;
|
||||
use std::io::{self, Seek, SeekFrom, Write};
|
||||
|
||||
pub trait TiffByteOrder: ByteOrder {
|
||||
@@ -52,6 +52,12 @@ impl<W: Write> TiffWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_i8(&mut self, n: i8) -> Result<(), io::Error> {
|
||||
self.writer.write_i8(n)?;
|
||||
self.offset += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_u16(&mut self, n: u16) -> Result<(), io::Error> {
|
||||
self.writer.write_u16::<NativeEndian>(n)?;
|
||||
self.offset += 2;
|
||||
@@ -59,6 +65,13 @@ impl<W: Write> TiffWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_i16(&mut self, n: i16) -> Result<(), io::Error> {
|
||||
self.writer.write_i16::<NativeEndian>(n)?;
|
||||
self.offset += 2;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_u32(&mut self, n: u32) -> Result<(), io::Error> {
|
||||
self.writer.write_u32::<NativeEndian>(n)?;
|
||||
self.offset += 4;
|
||||
@@ -66,6 +79,13 @@ impl<W: Write> TiffWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_i32(&mut self, n: i32) -> Result<(), io::Error> {
|
||||
self.writer.write_i32::<NativeEndian>(n)?;
|
||||
self.offset += 4;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_u64(&mut self, n: u64) -> Result<(), io::Error> {
|
||||
self.writer.write_u64::<NativeEndian>(n)?;
|
||||
self.offset += 8;
|
||||
@@ -78,6 +98,7 @@ impl<W: Write> TiffWriter<W> {
|
||||
let padding = [0, 0, 0];
|
||||
let padd_len = 4 - (self.offset % 4);
|
||||
self.writer.write_all(&padding[..padd_len as usize])?;
|
||||
self.offset += padd_len;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+85
-9
@@ -3,26 +3,38 @@ use std::fmt;
|
||||
use std::io;
|
||||
use std::string;
|
||||
|
||||
use decoder::ifd::{Tag, Value};
|
||||
use decoder::{CompressionMethod, PhotometricInterpretation, PlanarConfiguration};
|
||||
use decoder::ifd::Value;
|
||||
use miniz_oxide::inflate::TINFLStatus;
|
||||
use tags::{CompressionMethod, PhotometricInterpretation, PlanarConfiguration, Tag};
|
||||
use ColorType;
|
||||
|
||||
/// Tiff error kinds.
|
||||
#[derive(Debug)]
|
||||
pub enum TiffError {
|
||||
/// The Image is not formatted properly
|
||||
/// The Image is not formatted properly.
|
||||
FormatError(TiffFormatError),
|
||||
|
||||
/// The Decoder does not support this image format
|
||||
/// The Decoder does not support features required by the image.
|
||||
UnsupportedError(TiffUnsupportedError),
|
||||
|
||||
/// An I/O Error occurred while decoding the image
|
||||
/// An I/O Error occurred while decoding the image.
|
||||
IoError(io::Error),
|
||||
|
||||
/// The Limits of the Decoder is exceeded,
|
||||
/// The Limits of the Decoder is exceeded.
|
||||
LimitsExceeded,
|
||||
|
||||
/// 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 is not formatted properly.
|
||||
///
|
||||
/// This indicates that the encoder producing the image might behave incorrectly or that the input
|
||||
/// file has been corrupted.
|
||||
///
|
||||
/// The list of variants may grow to incorporate errors of future features. Matching against this
|
||||
/// exhaustively is not covered by interface stability guarantees.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum TiffFormatError {
|
||||
TiffSignatureNotFound,
|
||||
@@ -30,9 +42,15 @@ pub enum TiffFormatError {
|
||||
ImageFileDirectoryNotFound,
|
||||
InconsistentSizesEncountered,
|
||||
InvalidTag,
|
||||
InvalidTagValueType(Tag),
|
||||
RequiredTagNotFound(Tag),
|
||||
UnknownPredictor(u32),
|
||||
UnknownPredictor(u16),
|
||||
UnsignedIntegerExpected(Value),
|
||||
SignedIntegerExpected(Value),
|
||||
InflateError(InflateError),
|
||||
#[doc(hidden)]
|
||||
/// Do not match against this variant. It may get removed.
|
||||
__NonExhaustive,
|
||||
}
|
||||
|
||||
impl fmt::Display for TiffFormatError {
|
||||
@@ -44,6 +62,9 @@ impl fmt::Display for TiffFormatError {
|
||||
ImageFileDirectoryNotFound => write!(fmt, "Image file directory not found."),
|
||||
InconsistentSizesEncountered => write!(fmt, "Inconsistent sizes encountered."),
|
||||
InvalidTag => write!(fmt, "Image contains invalid tag."),
|
||||
InvalidTagValueType(ref tag) => {
|
||||
write!(fmt, "Tag `{:?}` did not have the expected value type.", tag)
|
||||
}
|
||||
RequiredTagNotFound(ref tag) => write!(fmt, "Required tag `{:?}` not found.", tag),
|
||||
UnknownPredictor(ref predictor) => {
|
||||
write!(fmt, "Unknown predictor “{}” encountered", predictor)
|
||||
@@ -51,10 +72,41 @@ impl fmt::Display for TiffFormatError {
|
||||
UnsignedIntegerExpected(ref val) => {
|
||||
write!(fmt, "Expected unsigned integer, {:?} found.", val)
|
||||
}
|
||||
SignedIntegerExpected(ref val) => {
|
||||
write!(fmt, "Expected signed integer, {:?} found.", val)
|
||||
}
|
||||
InflateError(_) => write!(fmt, "Failed to decode inflate data."),
|
||||
__NonExhaustive => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// implementation has been planned but not yet completed. Some variants may become unused over
|
||||
/// time and will then get deprecated before being removed.
|
||||
///
|
||||
/// The list of variants may grow. Matching against this exhaustively is not covered by interface
|
||||
/// stability guarantees.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum TiffUnsupportedError {
|
||||
HorizontalPredictor(ColorType),
|
||||
@@ -67,6 +119,9 @@ pub enum TiffUnsupportedError {
|
||||
UnsupportedBitsPerChannel(u8),
|
||||
UnsupportedPlanarConfig(Option<PlanarConfiguration>),
|
||||
UnsupportedDataType,
|
||||
#[doc(hidden)]
|
||||
/// Do not match against this variant. It may get removed.
|
||||
__NonExhaustive,
|
||||
}
|
||||
|
||||
impl fmt::Display for TiffUnsupportedError {
|
||||
@@ -92,7 +147,7 @@ impl fmt::Display for TiffUnsupportedError {
|
||||
write!(fmt, "Compression method {:?} is unsupported", method)
|
||||
}
|
||||
UnsupportedSampleDepth(samples) => {
|
||||
write!(fmt, "{} samples per pixel is supported.", samples)
|
||||
write!(fmt, "{} samples per pixel is unsupported.", samples)
|
||||
}
|
||||
UnsupportedColorType(color_type) => {
|
||||
write!(fmt, "Color type {:?} is unsupported", color_type)
|
||||
@@ -104,6 +159,7 @@ impl fmt::Display for TiffUnsupportedError {
|
||||
write!(fmt, "Unsupported planar configuration “{:?}”.", config)
|
||||
}
|
||||
UnsupportedDataType => write!(fmt, "Unsupported data type."),
|
||||
__NonExhaustive => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,6 +176,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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,10 +188,11 @@ impl Error for TiffError {
|
||||
TiffError::UnsupportedError(..) => "Unsupported error",
|
||||
TiffError::IoError(..) => "IO error",
|
||||
TiffError::LimitsExceeded => "Decoder limits exceeded",
|
||||
TiffError::IntSizeError => "Platform or format size limits exceeded",
|
||||
}
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&Error> {
|
||||
fn cause(&self) -> Option<&dyn Error> {
|
||||
match *self {
|
||||
TiffError::IoError(ref e) => Some(e),
|
||||
_ => None,
|
||||
@@ -154,5 +212,23 @@ impl From<string::FromUtf8Error> for TiffError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TiffFormatError> for TiffError {
|
||||
fn from(err: TiffFormatError) -> TiffError {
|
||||
TiffError::FormatError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TiffUnsupportedError> for TiffError {
|
||||
fn from(err: TiffUnsupportedError) -> TiffError {
|
||||
TiffError::UnsupportedError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::num::TryFromIntError> for TiffError {
|
||||
fn from(_err: std::num::TryFromIntError) -> TiffError {
|
||||
TiffError::IntSizeError
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of an image decoding/encoding process
|
||||
pub type TiffResult<T> = Result<T, TiffError>;
|
||||
+3
-4
@@ -8,15 +8,14 @@
|
||||
|
||||
extern crate byteorder;
|
||||
extern crate lzw;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
extern crate num_traits;
|
||||
extern crate miniz_oxide;
|
||||
|
||||
pub mod decoder;
|
||||
pub mod encoder;
|
||||
mod error;
|
||||
pub mod tags;
|
||||
|
||||
pub use self::error::{TiffError, TiffFormatError, TiffResult, TiffUnsupportedError};
|
||||
pub use self::error::{InflateError, TiffError, TiffFormatError, TiffResult, TiffUnsupportedError};
|
||||
|
||||
/// An enumeration over supported color types and their bit depths
|
||||
#[derive(Copy, PartialEq, Eq, Debug, Clone, Hash)]
|
||||
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
macro_rules! tags {
|
||||
{
|
||||
// Permit arbitrary meta items, which include documentation.
|
||||
$( #[$enum_attr:meta] )*
|
||||
$vis:vis enum $name:ident($ty:tt) $(unknown($unknown_doc:literal))* {
|
||||
// Each of the `Name = Val,` permitting documentation.
|
||||
$($(#[$ident_attr:meta])* $tag:ident = $val:expr,)*
|
||||
}
|
||||
} => {
|
||||
$( #[$enum_attr] )*
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum $name {
|
||||
$($(#[$ident_attr])* $tag,)*
|
||||
// FIXME: switch to non_exhaustive once stabilized and compiler requirement new enough
|
||||
#[doc(hidden)]
|
||||
__NonExhaustive,
|
||||
$(
|
||||
#[doc = $unknown_doc]
|
||||
Unknown($ty),
|
||||
)*
|
||||
}
|
||||
|
||||
impl $name {
|
||||
#[inline(always)]
|
||||
fn __from_inner_type(n: $ty) -> Result<Self, $ty> {
|
||||
match n {
|
||||
$( $val => Ok($name::$tag), )*
|
||||
n => Err(n),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn __to_inner_type(&self) -> $ty {
|
||||
match *self {
|
||||
$( $name::$tag => $val, )*
|
||||
$( $name::Unknown(n) => { $unknown_doc; n }, )*
|
||||
$name::__NonExhaustive => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tags!($name, $ty);
|
||||
};
|
||||
// For u16 tags, provide direct inherent primitive conversion methods.
|
||||
($name:tt, u16) => {
|
||||
impl $name {
|
||||
#[inline(always)]
|
||||
pub fn from_u16(val: u16) -> Option<Self> {
|
||||
Self::__from_inner_type(val).ok()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn to_u16(&self) -> u16 {
|
||||
Self::__to_inner_type(self)
|
||||
}
|
||||
}
|
||||
};
|
||||
// For other tag types, do nothing for now. With concat_idents one could
|
||||
// provide inherent conversion methods for all types.
|
||||
($name:tt, $ty:tt) => {};
|
||||
}
|
||||
|
||||
// Note: These tags appear in the order they are mentioned in the TIFF reference
|
||||
tags! {
|
||||
/// TIFF tags
|
||||
pub enum Tag(u16) unknown("A private or extension tag") {
|
||||
// Baseline tags:
|
||||
Artist = 315,
|
||||
// grayscale images PhotometricInterpretation 1 or 3
|
||||
BitsPerSample = 258,
|
||||
CellLength = 265, // TODO add support
|
||||
CellWidth = 264, // TODO add support
|
||||
// palette-color images (PhotometricInterpretation 3)
|
||||
ColorMap = 320, // TODO add support
|
||||
Compression = 259, // TODO add support for 2 and 32773
|
||||
Copyright = 33_432,
|
||||
DateTime = 306,
|
||||
ExtraSamples = 338, // TODO add support
|
||||
FillOrder = 266, // TODO add support
|
||||
FreeByteCounts = 289, // TODO add support
|
||||
FreeOffsets = 288, // TODO add support
|
||||
GrayResponseCurve = 291, // TODO add support
|
||||
GrayResponseUnit = 290, // TODO add support
|
||||
HostComputer = 316,
|
||||
ImageDescription = 270,
|
||||
ImageLength = 257,
|
||||
ImageWidth = 256,
|
||||
Make = 271,
|
||||
MaxSampleValue = 281, // TODO add support
|
||||
MinSampleValue = 280, // TODO add support
|
||||
Model = 272,
|
||||
NewSubfileType = 254, // TODO add support
|
||||
Orientation = 274, // TODO add support
|
||||
PhotometricInterpretation = 262,
|
||||
PlanarConfiguration = 284,
|
||||
ResolutionUnit = 296, // TODO add support
|
||||
RowsPerStrip = 278,
|
||||
SamplesPerPixel = 277,
|
||||
Software = 305,
|
||||
StripByteCounts = 279,
|
||||
StripOffsets = 273,
|
||||
SubfileType = 255, // TODO add support
|
||||
Threshholding = 263, // TODO add support
|
||||
XResolution = 282,
|
||||
YResolution = 283,
|
||||
// Advanced tags
|
||||
Predictor = 317,
|
||||
}
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
pub fn from_u16_exhaustive(val: u16) -> Self {
|
||||
Self::from_u16(val).unwrap_or_else(|| Tag::Unknown(val))
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
/// The type of an IFD entry (a 2 byte field).
|
||||
pub enum Type(u16) {
|
||||
BYTE = 1,
|
||||
ASCII = 2,
|
||||
SHORT = 3,
|
||||
LONG = 4,
|
||||
RATIONAL = 5,
|
||||
SBYTE = 6,
|
||||
SSHORT = 8,
|
||||
SLONG = 9,
|
||||
SRATIONAL = 10,
|
||||
/// BigTIFF 64-bit unsigned integer
|
||||
LONG8 = 16,
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
pub enum CompressionMethod(u16) {
|
||||
None = 1,
|
||||
Huffman = 2,
|
||||
Fax3 = 3,
|
||||
Fax4 = 4,
|
||||
LZW = 5,
|
||||
JPEG = 6,
|
||||
Deflate = 8,
|
||||
OldDeflate = 0x80B2,
|
||||
PackBits = 0x8005,
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
pub enum PhotometricInterpretation(u16) {
|
||||
WhiteIsZero = 0,
|
||||
BlackIsZero = 1,
|
||||
RGB = 2,
|
||||
RGBPalette = 3,
|
||||
TransparencyMask = 4,
|
||||
CMYK = 5,
|
||||
YCbCr = 6,
|
||||
CIELab = 8,
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
pub enum PlanarConfiguration(u16) {
|
||||
Chunky = 1,
|
||||
Planar = 2,
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
pub enum Predictor(u16) {
|
||||
None = 1,
|
||||
Horizontal = 2,
|
||||
}
|
||||
}
|
||||
|
||||
tags! {
|
||||
/// Type to represent resolution units
|
||||
pub enum ResolutionUnit(u16) {
|
||||
None = 1,
|
||||
Inch = 2,
|
||||
Centimeter = 3,
|
||||
}
|
||||
}
|
||||
+96
-30
@@ -4,59 +4,125 @@ use tiff::decoder::{ifd, Decoder, DecodingResult};
|
||||
use tiff::ColorType;
|
||||
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn test_gray_u8() {
|
||||
let img_file =
|
||||
File::open("./tests/images/minisblack-1c-8b.tiff").expect("Cannot find test image!");
|
||||
const TEST_IMAGE_DIR: &str = "./tests/images/";
|
||||
|
||||
macro_rules! test_image_sum {
|
||||
($name:ident, $buffer:ident, $sum_ty:ty) => {
|
||||
fn $name(file: &str, expected_type: ColorType, expected_sum: $sum_ty) {
|
||||
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(), ColorType::Gray(8));
|
||||
let img_res = decoder.read_image();
|
||||
assert!(img_res.is_ok());
|
||||
assert_eq!(decoder.colortype().unwrap(), expected_type);
|
||||
let img_res = decoder.read_image().unwrap();
|
||||
|
||||
match img_res {
|
||||
DecodingResult::$buffer(res) => {
|
||||
let sum: $sum_ty = res.into_iter().map(<$sum_ty>::from).sum();
|
||||
assert_eq!(sum, expected_sum);
|
||||
}
|
||||
_ => panic!("Wrong bit depth"),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test_image_sum!(test_image_sum_u8, U8, u64);
|
||||
test_image_sum!(test_image_sum_u16, U16, u64);
|
||||
test_image_sum!(test_image_sum_u32, U32, u64);
|
||||
test_image_sum!(test_image_sum_u64, U64, u64);
|
||||
|
||||
/// Tests that a decoder can be constructed for an image and the color type
|
||||
/// read from the IFD and is of the appropriate type, but the type is
|
||||
/// unsupported.
|
||||
fn test_image_color_type_unsupported(file: &str, expected_type: ColorType) {
|
||||
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);
|
||||
assert!(match decoder.read_image() {
|
||||
Err(tiff::TiffError::UnsupportedError(
|
||||
tiff::TiffUnsupportedError::UnsupportedColorType(_),
|
||||
)) => true,
|
||||
_ => false,
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u8() {
|
||||
let img_file = File::open("./tests/images/rgb-3c-8b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(8));
|
||||
let img_res = decoder.read_image();
|
||||
assert!(img_res.is_ok());
|
||||
fn test_cmyk_u8() {
|
||||
test_image_sum_u8("cmyk-3c-8b.tiff", ColorType::CMYK(8), 8522658);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cmyk_u16() {
|
||||
test_image_sum_u16("cmyk-3c-16b.tiff", ColorType::CMYK(16), 2181426827);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u8() {
|
||||
test_image_sum_u8("minisblack-1c-8b.tiff", ColorType::Gray(8), 2840893);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u12() {
|
||||
test_image_color_type_unsupported("12bit.cropped.tiff", ColorType::Gray(12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u16() {
|
||||
let img_file =
|
||||
File::open("./tests/images/minisblack-1c-16b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::Gray(16));
|
||||
let img_res = decoder.read_image();
|
||||
assert!(img_res.is_ok());
|
||||
test_image_sum_u16("minisblack-1c-16b.tiff", ColorType::Gray(16), 733126239);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u32() {
|
||||
test_image_sum_u32("gradient-1c-32b.tiff", ColorType::Gray(32), 549892913787);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u64() {
|
||||
test_image_sum_u64("gradient-1c-64b.tiff", ColorType::Gray(64), 549892913787);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u8() {
|
||||
test_image_sum_u8("rgb-3c-8b.tiff", ColorType::RGB(8), 7842108);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u12() {
|
||||
test_image_color_type_unsupported("12bit.cropped.rgb.tiff", ColorType::RGB(12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u16() {
|
||||
let img_file = File::open("./tests/images/rgb-3c-16b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(16));
|
||||
let img_res = decoder.read_image();
|
||||
assert!(img_res.is_ok());
|
||||
test_image_sum_u16("rgb-3c-16b.tiff", ColorType::RGB(16), 2024349944);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u32() {
|
||||
test_image_sum_u32("gradient-3c-32b.tiff", ColorType::RGB(32), 2030834111716);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u64() {
|
||||
test_image_sum_u64("gradient-3c-64b.tiff", ColorType::RGB(64), 2030834111716);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_tags() {
|
||||
// these files have null-terminated strings for their Software tag. One has extra bytes after
|
||||
// the null byte, so we check both to ensure that we're truncating properly
|
||||
let filenames = vec!["minisblack-1c-16b.tiff", "rgb-3c-16b.tiff"];
|
||||
let filenames = ["minisblack-1c-16b.tiff", "rgb-3c-16b.tiff"];
|
||||
for filename in filenames.iter() {
|
||||
let path = format!("./tests/images/{}", filename);
|
||||
let img_file = File::open(path).expect("can't open file");
|
||||
let path = PathBuf::from(TEST_IMAGE_DIR).join(filename);
|
||||
let img_file = File::open(path).expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
let software = decoder.get_tag(ifd::Tag::Software).unwrap();
|
||||
let software = decoder.get_tag(tiff::tags::Tag::Software).unwrap();
|
||||
match software {
|
||||
ifd::Value::Ascii(s) => assert_eq!(
|
||||
s,
|
||||
String::from("GraphicsMagick 1.2 unreleased Q16 http://www.GraphicsMagick.org/")
|
||||
&s,
|
||||
"GraphicsMagick 1.2 unreleased Q16 http://www.GraphicsMagick.org/"
|
||||
),
|
||||
_ => assert!(false),
|
||||
};
|
||||
|
||||
+346
-82
@@ -1,12 +1,13 @@
|
||||
extern crate tempfile;
|
||||
extern crate tiff;
|
||||
|
||||
use tiff::decoder::{Decoder, DecodingResult};
|
||||
use tiff::encoder::{colortype, TiffEncoder};
|
||||
use tiff::encoder::{colortype, SRational, TiffEncoder};
|
||||
use tiff::tags::Tag;
|
||||
use tiff::ColorType;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{Cursor, Seek, SeekFrom};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn encode_decode() {
|
||||
@@ -19,7 +20,7 @@ fn encode_decode() {
|
||||
image_data.push(val);
|
||||
}
|
||||
}
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
|
||||
@@ -53,125 +54,388 @@ fn test_encode_undersized_buffer() {
|
||||
}
|
||||
}
|
||||
|
||||
const TEST_IMAGE_DIR: &str = "./tests/images/";
|
||||
|
||||
#[test]
|
||||
fn test_gray_u8_roundtrip() {
|
||||
let img_file =
|
||||
File::open("./tests/images/minisblack-1c-8b.tiff").expect("Cannot find test image!");
|
||||
macro_rules! test_roundtrip {
|
||||
($name:ident, $buffer:ident, $buffer_ty:ty) => {
|
||||
fn $name<C: colortype::ColorType<Inner = $buffer_ty>>(
|
||||
file: &str,
|
||||
expected_type: ColorType,
|
||||
) {
|
||||
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(), ColorType::Gray(8));
|
||||
assert_eq!(decoder.colortype().unwrap(), expected_type);
|
||||
|
||||
let image_data = match decoder.read_image().unwrap() {
|
||||
DecodingResult::U8(res) => res,
|
||||
DecodingResult::$buffer(res) => res,
|
||||
_ => panic!("Wrong data type"),
|
||||
};
|
||||
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
|
||||
let (width, height) = decoder.dimensions().unwrap();
|
||||
tiff.write_image::<colortype::Gray8>(width, height, &image_data)
|
||||
.unwrap();
|
||||
tiff.write_image::<C>(width, height, &image_data).unwrap();
|
||||
}
|
||||
file.seek(SeekFrom::Start(0)).unwrap();
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut file).unwrap();
|
||||
if let DecodingResult::U8(img_res) = decoder.read_image().unwrap() {
|
||||
if let DecodingResult::$buffer(img_res) = decoder.read_image().unwrap() {
|
||||
assert_eq!(image_data, img_res);
|
||||
} else {
|
||||
panic!("Wrong data type");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test_roundtrip!(test_u8_roundtrip, U8, u8);
|
||||
test_roundtrip!(test_u16_roundtrip, U16, u16);
|
||||
test_roundtrip!(test_u32_roundtrip, U32, u32);
|
||||
test_roundtrip!(test_u64_roundtrip, U64, u64);
|
||||
|
||||
#[test]
|
||||
fn test_gray_u8_roundtrip() {
|
||||
test_u8_roundtrip::<colortype::Gray8>("minisblack-1c-8b.tiff", ColorType::Gray(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u8_roundtrip() {
|
||||
let img_file = File::open("./tests/images/rgb-3c-8b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(8));
|
||||
|
||||
let image_data = match decoder.read_image().unwrap() {
|
||||
DecodingResult::U8(res) => res,
|
||||
_ => panic!("Wrong data type"),
|
||||
};
|
||||
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
|
||||
let (width, height) = decoder.dimensions().unwrap();
|
||||
tiff.write_image::<colortype::RGB8>(width, height, &image_data)
|
||||
.unwrap();
|
||||
}
|
||||
file.seek(SeekFrom::Start(0)).unwrap();
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut file).unwrap();
|
||||
if let DecodingResult::U8(img_res) = decoder.read_image().unwrap() {
|
||||
assert_eq!(image_data, img_res);
|
||||
} else {
|
||||
panic!("Wrong data type");
|
||||
}
|
||||
test_u8_roundtrip::<colortype::RGB8>("rgb-3c-8b.tiff", ColorType::RGB(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cmyk_u8_roundtrip() {
|
||||
test_u8_roundtrip::<colortype::CMYK8>("cmyk-3c-8b.tiff", ColorType::CMYK(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u16_roundtrip() {
|
||||
let img_file =
|
||||
File::open("./tests/images/minisblack-1c-16b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::Gray(16));
|
||||
|
||||
let image_data = match decoder.read_image().unwrap() {
|
||||
DecodingResult::U16(res) => res,
|
||||
_ => panic!("Wrong data type"),
|
||||
};
|
||||
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
|
||||
let (width, height) = decoder.dimensions().unwrap();
|
||||
tiff.write_image::<colortype::Gray16>(width, height, &image_data)
|
||||
.unwrap();
|
||||
}
|
||||
file.seek(SeekFrom::Start(0)).unwrap();
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut file).unwrap();
|
||||
if let DecodingResult::U16(img_res) = decoder.read_image().unwrap() {
|
||||
assert_eq!(image_data, img_res);
|
||||
} else {
|
||||
panic!("Wrong data type");
|
||||
}
|
||||
}
|
||||
test_u16_roundtrip::<colortype::Gray16>("minisblack-1c-16b.tiff", ColorType::Gray(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u16_roundtrip() {
|
||||
let img_file = File::open("./tests/images/rgb-3c-16b.tiff").expect("Cannot find test image!");
|
||||
let mut decoder = Decoder::new(img_file).expect("Cannot create decoder");
|
||||
assert_eq!(decoder.colortype().unwrap(), ColorType::RGB(16));
|
||||
test_u16_roundtrip::<colortype::RGB16>("rgb-3c-16b.tiff", ColorType::RGB(16));
|
||||
}
|
||||
|
||||
let image_data = match decoder.read_image().unwrap() {
|
||||
DecodingResult::U16(res) => res,
|
||||
_ => panic!("Wrong data type"),
|
||||
};
|
||||
#[test]
|
||||
fn test_cmyk_u16_roundtrip() {
|
||||
test_u16_roundtrip::<colortype::CMYK16>("cmyk-3c-16b.tiff", ColorType::CMYK(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u32_roundtrip() {
|
||||
test_u32_roundtrip::<colortype::Gray32>("gradient-1c-32b.tiff", ColorType::Gray(32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u32_roundtrip() {
|
||||
test_u32_roundtrip::<colortype::RGB32>("gradient-3c-32b.tiff", ColorType::RGB(32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gray_u64_roundtrip() {
|
||||
test_u64_roundtrip::<colortype::Gray64>("gradient-1c-64b.tiff", ColorType::Gray(64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rgb_u64_roundtrip() {
|
||||
test_u64_roundtrip::<colortype::RGB64>("gradient-3c-64b.tiff", ColorType::RGB(64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_byte() {
|
||||
let mut data = Cursor::new(Vec::new());
|
||||
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
{
|
||||
let mut tiff = TiffEncoder::new(&mut file).unwrap();
|
||||
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();
|
||||
|
||||
let (width, height) = decoder.dimensions().unwrap();
|
||||
tiff.write_image::<colortype::RGB16>(width, height, &image_data)
|
||||
encoder.write_tag(Tag::Unknown(65000), &[1_u8][..]).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65001), &[1_u8, 2][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65002), &[1_u8, 2, 3][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65003), &[1_u8, 2, 3, 4][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65004), &[1_u8, 2, 3, 4, 5][..])
|
||||
.unwrap();
|
||||
}
|
||||
file.seek(SeekFrom::Start(0)).unwrap();
|
||||
|
||||
data.set_position(0);
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut file).unwrap();
|
||||
if let DecodingResult::U16(img_res) = decoder.read_image().unwrap() {
|
||||
assert_eq!(image_data, img_res);
|
||||
} else {
|
||||
panic!("Wrong data type");
|
||||
let mut decoder = Decoder::new(&mut data).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65000))
|
||||
.unwrap()
|
||||
.into_u32_vec()
|
||||
.unwrap(),
|
||||
[1]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65001))
|
||||
.unwrap()
|
||||
.into_u32_vec()
|
||||
.unwrap(),
|
||||
[1, 2]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65002))
|
||||
.unwrap()
|
||||
.into_u32_vec()
|
||||
.unwrap(),
|
||||
[1, 2, 3]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65003))
|
||||
.unwrap()
|
||||
.into_u32_vec()
|
||||
.unwrap(),
|
||||
[1, 2, 3, 4]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65004))
|
||||
.unwrap()
|
||||
.into_u32_vec()
|
||||
.unwrap(),
|
||||
[1, 2, 3, 4, 5]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Test writing signed tags from TIFF 6.0
|
||||
fn test_signed() {
|
||||
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), -1_i8).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65001), &[-1_i8][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65002), &[-1_i8, 2][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65003), &[-1_i8, 2, -3][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65004), &[-1_i8, 2, -3, 4][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65005), &[-1_i8, 2, -3, 4, -5][..])
|
||||
.unwrap();
|
||||
|
||||
encoder.write_tag(Tag::Unknown(65010), -1_i16).unwrap();
|
||||
encoder.write_tag(Tag::Unknown(65011), -1_i16).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65012), &[-1_i16, 2][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65013), &[-1_i16, 2, -3][..])
|
||||
.unwrap();
|
||||
|
||||
encoder.write_tag(Tag::Unknown(65020), -1_i32).unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65021), &[-1_i32][..])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65022), &[-1_i32, 2][..])
|
||||
.unwrap();
|
||||
|
||||
encoder
|
||||
.write_tag(Tag::Unknown(65030), SRational { n: -1, d: 100 })
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_tag(
|
||||
Tag::Unknown(65031),
|
||||
&[SRational { n: -1, d: 100 }, SRational { n: 2, d: 100 }][..],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
//Rewind the cursor for reading
|
||||
data.set_position(0);
|
||||
{
|
||||
let mut decoder = Decoder::new(&mut data).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65000))
|
||||
.unwrap()
|
||||
.into_i32()
|
||||
.unwrap(),
|
||||
-1,
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65001))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65002))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65003))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2, -3]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65004))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2, -3, 4]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65005))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2, -3, 4, -5],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65010))
|
||||
.unwrap()
|
||||
.into_i32()
|
||||
.unwrap(),
|
||||
-1
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65011))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65012))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65013))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2, -3]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65020))
|
||||
.unwrap()
|
||||
.into_i32()
|
||||
.unwrap(),
|
||||
-1
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65021))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65022))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 2]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65030))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1, 100]
|
||||
);
|
||||
assert_eq!(
|
||||
decoder
|
||||
.get_tag(Tag::Unknown(65031))
|
||||
.unwrap()
|
||||
.into_i32_vec()
|
||||
.unwrap(),
|
||||
[-1_i32, 100, 2, 100]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// check multipage image handling
|
||||
fn test_multipage_image() {
|
||||
let mut img_file = Cursor::new(Vec::new());
|
||||
|
||||
{
|
||||
// first create a multipage image with 2 images
|
||||
let mut img_encoder = TiffEncoder::new(&mut img_file).unwrap();
|
||||
|
||||
// write first grayscale image (2x2 16-bit)
|
||||
let img1: Vec<u16> = [1, 2, 3, 4].to_vec();
|
||||
img_encoder
|
||||
.write_image::<colortype::Gray16>(2, 2, &img1[..])
|
||||
.unwrap();
|
||||
// write second grayscale image (3x3 8-bit)
|
||||
let img2: Vec<u8> = [9, 8, 7, 6, 5, 4, 3, 2, 1].to_vec();
|
||||
img_encoder
|
||||
.write_image::<colortype::Gray8>(3, 3, &img2[..])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// seek to the beginning of the file, so that it can be decoded
|
||||
img_file.seek(SeekFrom::Start(0)).unwrap();
|
||||
|
||||
{
|
||||
let mut img_decoder = Decoder::new(&mut img_file).unwrap();
|
||||
|
||||
// check the dimensions of the image in the first page
|
||||
assert_eq!(img_decoder.dimensions().unwrap(), (2, 2));
|
||||
img_decoder.next_image().unwrap();
|
||||
// check the dimensions of the image in the second page
|
||||
assert_eq!(img_decoder.dimensions().unwrap(), (3, 3));
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user