| 1 | package PDF::Builder::Resource::XObject::Image::TIFF_GT; | ||
| 2 | |||
| 3 | use base 'PDF::Builder::Resource::XObject::Image'; | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | our $VERSION = '3.028'; # VERSION | ||
| 9 | our $LAST_UPDATE = '3.027'; # manually update whenever code is changed | ||
| 10 | |||
| 11 | use Compress::Zlib; | ||
| 12 | |||
| 13 | use PDF::Builder::Basic::PDF::Utils; | ||
| 14 | use PDF::Builder::Resource::XObject::Image::TIFF::File_GT; | ||
| 15 | use PDF::Builder::Util; | ||
| 16 | use Scalar::Util qw(weaken); | ||
| 17 | use Graphics::TIFF ':all'; # have already confirmed the appropriate version exists | ||
| 18 | |||
| 19 | =head1 NAME | ||
| 20 | |||
| 21 | PDF::Builder::Resource::XObject::Image::TIFF_GT - TIFF image support | ||
| 22 | (Graphics::TIFF enabled) | ||
| 23 | |||
| 24 | Inherits from L<PDF::Builder::Resource::XObject::Image> | ||
| 25 | |||
| 26 | =head1 METHODS | ||
| 27 | |||
| 28 | =head2 new | ||
| 29 | |||
| 30 | $res = PDF::Builder::Resource::XObject::Image::TIFF_GT->new($pdf, $file, %opts) | ||
| 31 | |||
| 32 | =over | ||
| 33 | |||
| 34 | Returns a TIFF-image object. C<$pdf> is the PDF object being added to, C<$file> | ||
| 35 | is the input TIFF file, and the optional C<$name> of the new parent image object | ||
| 36 | defaults to IxAAA. | ||
| 37 | |||
| 38 | If the Graphics::TIFF package is installed, and its use is not suppressed via | ||
| 39 | the C<nouseGT> flag (see Builder documentation for C<image_tiff>), the TIFF_GT | ||
| 40 | library will be used. Otherwise, the TIFF library will be used instead. | ||
| 41 | |||
| 42 | Options: | ||
| 43 | |||
| 44 | =over | ||
| 45 | |||
| 46 | =item 'notrans' => 1 | ||
| 47 | |||
| 48 | Ignore any alpha layer (transparency) and make the image fully opaque. | ||
| 49 | |||
| 50 | =item 'name' => 'string' | ||
| 51 | |||
| 52 | This is the name you can give for the TIFF image object. The default is Ixnnnn. | ||
| 53 | |||
| 54 | =back | ||
| 55 | |||
| 56 | TIFF support (when using Graphics::TIFF) is for C<PhotometricInterpretation> | ||
| 57 | values of 0 (bilevel/gray, white is 0), 1 (bilevel/gray, black is 0), 2 (RGB), | ||
| 58 | and 3 (Palette color). It currently does I<not> support 4 (transparency mask), | ||
| 59 | 5 (separated CMYK), 6 (YCbCr), 8 (CIELab), or higher. There is limited support | ||
| 60 | for an Alpha (transparency) channel (due to extremely limited test cases). | ||
| 61 | Some tags are not supported, and a PlanarConfiguration of 2 is unknown until | ||
| 62 | we get some test cases. | ||
| 63 | |||
| 64 | Some applications seem to take odd liberties with TIFF tags, such as adding a | ||
| 65 | SamplePerPixel without specifying ExtraSamples type. In such cases, we treat | ||
| 66 | one extra sample (not otherwise defined) as an Alpha channel, and hope for | ||
| 67 | the best! | ||
| 68 | |||
| 69 | If there are invalid tags or field values within a tag, the Graphics::TIFF | ||
| 70 | library will attempt to pop-up a warning dialog, rather than just ignoring | ||
| 71 | invalid things. If we can find a switch to disable this behavior, we will | ||
| 72 | look into adding it as an option. According to Graphic::TIFF's owner | ||
| 73 | (ticket RT 133955), this is coming directly from libtiff (as write to STDERR), | ||
| 74 | so he can't do anything about it! | ||
| 75 | |||
| 76 | Finally, while Graphics::TIFF does not directly support passing in a filehandle | ||
| 77 | (usually a GLOB), PDF::Builder will attempt to detect this issue and write the | ||
| 78 | content (from the filehandle) to a temporary file, and pass that in as a | ||
| 79 | normal file. Some operating systems appear to have trouble erasing this | ||
| 80 | temporary file, so be aware that such files may build up over time! | ||
| 81 | |||
| 82 | =back | ||
| 83 | |||
| 84 | =cut | ||
| 85 | |||
| 86 | sub new { | ||
| 87 | my ($class, $pdf, $file, %opts) = @_; | ||
| 88 | # copy dashed option names to preferred undashed names | ||
| 89 | if (defined $opts{'-nouseGT'} && !defined $opts{'nouseGT'}) { $opts{'nouseGT'} = delete($opts{'-nouseGT'}); } | ||
| 90 | if (defined $opts{'-name'} && !defined $opts{'name'}) { $opts{'name'} = delete($opts{'-name'}); } | ||
| 91 | if (defined $opts{'-compress'} && !defined $opts{'compress'}) { $opts{'compress'} = delete($opts{'-compress'}); } | ||
| 92 | if (defined $opts{'-notrans'} && !defined $opts{'notrans'}) { $opts{'notrans'} = delete($opts{'-notrans'}); } | ||
| 93 | |||
| 94 | my ($name, $compress); | ||
| 95 | if (exists $opts{'name'}) { $name = $opts{'name'}; } | ||
| 96 | #if (exists $opts{'compress'}) { $compress = $opts{'compress'}; } | ||
| 97 | |||
| 98 | my $self; | ||
| 99 | |||
| 100 | my $tif = PDF::Builder::Resource::XObject::Image::TIFF::File_GT->new($file, %opts); | ||
| 101 | |||
| 102 | # in case of problematic things | ||
| 103 | # proxy to other modules | ||
| 104 | |||
| 105 | $class = ref($class) if ref($class); | ||
| 106 | |||
| 107 | $self = $class->SUPER::new($pdf, $name || 'Ix'.pdfkey()); | ||
| 108 | $pdf->new_obj($self) unless $self->is_obj($pdf); | ||
| 109 | |||
| 110 | $self->{' apipdf'} = $pdf; | ||
| 111 | weaken $self->{' apipdf'}; | ||
| 112 | |||
| 113 | # set up dict stream for any Alpha channel to be split out from $buffer | ||
| 114 | my $dict = PDFDict(); | ||
| 115 | |||
| 116 | # let's try to clarify various strange tag combinations | ||
| 117 | # one extra SamplesPerPixel (2/4) and no ExtraSamples (or is 0)? | ||
| 118 | # treat as an Alpha channel with ExtraSamples 2 (unassociated alpha) | ||
| 119 | if ($tif->{'colorSpace'} eq 'DeviceGray' && | ||
| 120 | $tif->{'SamplesPerPixel'} == 2 && | ||
| 121 | (!defined $tif->{'ExtraSamples'} || $tif->{'ExtraSamples'} == 0)) { | ||
| 122 | # let's assume it's realy SPP 1 with ExtraSamples UNASSOC_ALPHA | ||
| 123 | $tif->{'SamplesPerPixel'} = 1; | ||
| 124 | $tif->{'ExtraSamples'} = EXTRASAMPLE_UNASSALPHA; # 2 | ||
| 125 | #print " changed SPP 2 to 1, ES 0 to 2, to treat as GA\n"; | ||
| 126 | } | ||
| 127 | if ($tif->{'colorSpace'} eq 'DeviceRGB' && | ||
| 128 | $tif->{'SamplesPerPixel'} == 4 && | ||
| 129 | (!defined $tif->{'ExtraSamples'} || $tif->{'ExtraSamples'} == 0)) { | ||
| 130 | # let's assume it's realy SPP 3 with ExtraSamples UNASSOC_ALPHA | ||
| 131 | $tif->{'SamplesPerPixel'} = 3; | ||
| 132 | $tif->{'ExtraSamples'} = EXTRASAMPLE_UNASSALPHA; # 2 | ||
| 133 | #print " changed SPP 4 to 3, ES 0 to 2, to treat as RGBA\n"; | ||
| 134 | } | ||
| 135 | # otherwise ExtraSamples is in order, but have "extra" sample | ||
| 136 | if ($tif->{'colorSpace'} eq 'DeviceGray' && | ||
| 137 | $tif->{'SamplesPerPixel'} == 2) { | ||
| 138 | $tif->{'SamplesPerPixel'} = 1; | ||
| 139 | } | ||
| 140 | if ($tif->{'colorSpace'} eq 'DeviceRGB' && | ||
| 141 | $tif->{'SamplesPerPixel'} == 4) { | ||
| 142 | $tif->{'SamplesPerPixel'} = 3; | ||
| 143 | } | ||
| 144 | |||
| 145 | $self->read_tiff($pdf, $tif, %opts); | ||
| 146 | |||
| 147 | $tif->close(); | ||
| 148 | |||
| 149 | return $self; | ||
| 150 | } # end of new() | ||
| 151 | |||
| 152 | =head2 usesLib | ||
| 153 | |||
| 154 | $mode = $tif->usesLib() | ||
| 155 | |||
| 156 | =over | ||
| 157 | |||
| 158 | Returns 1 if Graphics::TIFF installed and used, 0 if not installed, or -1 if | ||
| 159 | installed but not used (nouseGT option given to C<image_tiff>). | ||
| 160 | |||
| 161 | B<Caution:> this method can only be used I<after> the image object has been | ||
| 162 | created. It can't tell you whether Graphics::TIFF is available in | ||
| 163 | advance of actually using it, in case you want to use some functionality | ||
| 164 | available only in TIFF_GT. See the L<PDF::Builder> LA_GT() call if you | ||
| 165 | need to know in advance. | ||
| 166 | |||
| 167 | =back | ||
| 168 | |||
| 169 | =cut | ||
| 170 | |||
| 171 | sub usesLib { | ||
| 172 | my ($self) = shift; | ||
| 173 | # should be 1 for Graphics::TIFF is installed and used | ||
| 174 | return $self->{'usesGT'}->val(); | ||
| 175 | } | ||
| 176 | |||
| 177 | sub decode_all_strips { | ||
| 178 | my ($self, $tif) = @_; | ||
| 179 | $self->{' stream'} = ''; | ||
| 180 | for my $i (0 .. $tif->{object}->NumberOfStrips() - 1) { | ||
| 181 | $self->{' stream'} .= $tif->{object}->ReadEncodedStrip($i, -1); | ||
| 182 | } | ||
| 183 | return; | ||
| 184 | } | ||
| 185 | |||
| 186 | sub handle_alpha { | ||
| 187 | my ($self, $pdf, $tif, %opts) = @_; | ||
| 188 | my $transparency = (defined $opts{'notrans'} && $opts{'notrans'} == 1)? 0: 1; | ||
| 189 | my ($alpha, $dict); | ||
| 190 | |||
| 191 | # handle any Alpha channel/layer | ||
| 192 | my $h = $tif->{'imageHeight'}; # in pixels | ||
| 193 | my $w = $tif->{'imageWidth'}; | ||
| 194 | my $samples = 1; # fallback | ||
| 195 | |||
| 196 | if (defined $tif->{'ExtraSamples'} && | ||
| 197 | $tif->{'ExtraSamples'} == EXTRASAMPLE_ASSOCALPHA) { | ||
| 198 | # Gray or RGB pre-multiplication will likely have to be backed out | ||
| 199 | if ($tif->{'colorSpace'} eq 'DeviceGray') { | ||
| 200 | # Gray or Bilevel (pre-multiplied) + Alpha | ||
| 201 | $samples = 1; | ||
| 202 | } elsif ($tif->{'colorSpace'} eq 'DeviceRGB') { | ||
| 203 | # RGB (pre-multiplied) + Alpha | ||
| 204 | $samples = 3; | ||
| 205 | } else { | ||
| 206 | warn "Invalid TIFF file, requested Alpha for $tif->{'colorSpace'}". | ||
| 207 | ", PDF will likely be defective!\n"; | ||
| 208 | } | ||
| 209 | ($self->{' stream'}, $alpha) = | ||
| 210 | split_alpha($self->{' stream'}, $samples, $tif->{'bitsPerSample'}, $w, $h); | ||
| 211 | $self->{' stream'} = | ||
| 212 | descale($self->{' stream'}, $samples, $tif->{'bitsPerSample'}, $alpha, $w*$h); | ||
| 213 | } elsif (defined $tif->{'ExtraSamples'} && | ||
| 214 | $tif->{'ExtraSamples'} == EXTRASAMPLE_UNASSALPHA) { | ||
| 215 | # Gray or RGB at full value, no adjustment needed | ||
| 216 | if ($tif->{'colorSpace'} eq 'DeviceGray') { | ||
| 217 | # Gray or Bilevel + Alpha | ||
| 218 | $samples = 1; | ||
| 219 | } elsif ($tif->{'colorSpace'} eq 'DeviceRGB') { | ||
| 220 | # RGB + Alpha | ||
| 221 | $samples = 3; | ||
| 222 | } else { | ||
| 223 | warn "Invalid TIFF file, requested Alpha for $tif->{'colorSpace'}". | ||
| 224 | ", PDF will likely be defective!\n"; | ||
| 225 | } | ||
| 226 | ($self->{' stream'}, $alpha) = | ||
| 227 | split_alpha($self->{' stream'}, $samples, $tif->{'bitsPerSample'}, $w, $h); | ||
| 228 | } | ||
| 229 | |||
| 230 | # $alpha is undef if no alpha layer found | ||
| 231 | if (defined $alpha and $transparency) { | ||
| 232 | $dict = PDFDict(); | ||
| 233 | $pdf->new_obj($dict); | ||
| 234 | $dict->{'Type'} = PDFName('XObject'); | ||
| 235 | $dict->{'Subtype'} = PDFName('Image'); | ||
| 236 | $dict->{'Width'} = PDFNum($w); | ||
| 237 | $dict->{'Height'} = PDFNum($h); | ||
| 238 | $dict->{'ColorSpace'} = PDFName('DeviceGray'); # Alpha is always | ||
| 239 | $dict->{'BitsPerComponent'} = PDFNum($tif->{'bitsPerSample'}); | ||
| 240 | $self->{'SMask'} = $dict; | ||
| 241 | $dict->{' stream'} = $alpha; | ||
| 242 | } | ||
| 243 | return $dict; | ||
| 244 | } | ||
| 245 | |||
| 246 | # non-CCITT compression methods | ||
| 247 | sub handle_generic { | ||
| 248 | my ($self, $pdf, $tif, %opts) = @_; | ||
| 249 | |||
| 250 | # colorspace DeviceGray or DeviceRGB already set in read_tiff() | ||
| 251 | # bits_per_component 1 2 4 8 16? already set in read_tiff() | ||
| 252 | my $dict = PDFDict(); | ||
| 253 | $self->{'DecodeParms'} = PDFArray($dict); | ||
| 254 | $dict->{'BitsPerComponent'} = PDFNum($tif->{'bitsPerSample'}); | ||
| 255 | $dict->{'Colors'} = PDFNum($tif->{'colorSpace'} eq 'DeviceGray'?1 :3); | ||
| 256 | |||
| 257 | # uncompressed bilevel needs to be flipped | ||
| 258 | if (!defined $tif->{'filter'} && $tif->{'bitsPerSample'} == 1) { | ||
| 259 | $self->{'Decode'} = PDFArray(PDFNum(1), PDFNum(0)); | ||
| 260 | } | ||
| 261 | $self->decode_all_strips($tif); | ||
| 262 | my $alpha = $self->handle_alpha($pdf, $tif, %opts); | ||
| 263 | |||
| 264 | # compress all but short streams | ||
| 265 | if (length($self->{' stream'}) > 32) { | ||
| 266 | $self->{' stream'} = Compress::Zlib::compress($self->{' stream'}); | ||
| 267 | $self->filters('FlateDecode'); # tell reader it's compressed... | ||
| 268 | } else { | ||
| 269 | # too short to bother compressing. '/Filter [ /FlateDecode ] ' | ||
| 270 | # takes up 25 bytes all by itself | ||
| 271 | delete $self->{'Filter'}; | ||
| 272 | } | ||
| 273 | $self->{' nofilt'} = 1; | ||
| 274 | if (defined $alpha and $alpha->{' stream'}) { # there is transparency? | ||
| 275 | if (length($alpha->{' stream'}) > 32) { | ||
| 276 | $alpha->{' stream'} = Compress::Zlib::compress($alpha->{' stream'}); | ||
| 277 | $alpha->filters('FlateDecode'); # tell reader it's compressed... | ||
| 278 | } else { | ||
| 279 | # too short to bother compressing. '/Filter [ /FlateDecode ] ' | ||
| 280 | # takes up 25 bytes all by itself | ||
| 281 | delete $alpha->{'Filter'}; | ||
| 282 | } | ||
| 283 | $alpha->{' nofilt'} = 1; | ||
| 284 | } | ||
| 285 | |||
| 286 | return $self; | ||
| 287 | } # end of handle_generic() | ||
| 288 | |||
| 289 | # split alpha from buffer (both strings) | ||
| 290 | # bps = width of a sample in bits, samples 1 (G) or 3 (RGB) | ||
| 291 | # returns $buffer and $alpha strings | ||
| 292 | # TBD: fill order or other directional issues? | ||
| 293 | sub split_alpha { | ||
| 294 | my ($inbuf, $samples, $bps, $w, $h) = @_; | ||
| 295 | my $count = $w * $h; | ||
| 296 | my $outbuf = ''; | ||
| 297 | my $alpha = ''; | ||
| 298 | |||
| 299 | ## debug | ||
| 300 | #my @slice; # TEMP | ||
| 301 | #if ($count == 999*1056) { | ||
| 302 | # # French text pag1.tif | ||
| 303 | # @slice = (823*999, 823*999+125); # row 824/1056 | ||
| 304 | #}elsif($count == 1000*568) { | ||
| 305 | # # Lorem ipsum alpha.tif | ||
| 306 | # @slice = (283*1000, 283*1000+125); # row 284/568 | ||
| 307 | #}else{ | ||
| 308 | # @slice = (-1, -1); | ||
| 309 | #} | ||
| 310 | |||
| 311 | ## debug | ||
| 312 | ## upon entry, what is raw input row? # TEMP | ||
| 313 | #if ($slice[0]>-1 && $bps==16){ | ||
| 314 | # print "bps==16 raw input slice: "; | ||
| 315 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 316 | # my $pixel = substr($inbuf, $i*($samples+1)*2, ($samples+1)*2); | ||
| 317 | # my @pixelbytes = split //, $pixel; | ||
| 318 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 319 | # print " "; | ||
| 320 | # } | ||
| 321 | # print "\n"; | ||
| 322 | #} | ||
| 323 | #if ($slice[0]>-1 && $bps==8){ | ||
| 324 | # print "bps==8 raw input slice: "; | ||
| 325 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 326 | # my $pixel = substr($inbuf, $i*($samples+1), $samples+1); | ||
| 327 | # my @pixelbytes = split //, $pixel; | ||
| 328 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 329 | # print " "; | ||
| 330 | # } | ||
| 331 | # print "\n"; | ||
| 332 | #} | ||
| 333 | ## bps<8 is ugly to dump and not worth doing | ||
| 334 | |||
| 335 | # COULD have different number of bits per sample, unless GT prevents this | ||
| 336 | if ($bps == 16) { | ||
| 337 | # full double bytes to work with (not sure if 16bps in TIFF) | ||
| 338 | for (my $i=0; $i<$count; $i++) { | ||
| 339 | substr($outbuf, $i*$samples*2, $samples*2) = | ||
| 340 | substr($inbuf, $i*($samples+1)*2, $samples*2); | ||
| 341 | substr($alpha, $i*2, 2) = | ||
| 342 | substr($inbuf, $i*($samples+1)*2+$samples*2, 2); | ||
| 343 | } | ||
| 344 | } elsif ($bps == 8) { | ||
| 345 | # full bytes to work with | ||
| 346 | for (my $i=0; $i<$count; $i++) { | ||
| 347 | substr($outbuf, $i*$samples, $samples) = | ||
| 348 | substr($inbuf, $i*($samples+1), $samples); | ||
| 349 | substr($alpha, $i, 1) = | ||
| 350 | substr($inbuf, $i*($samples+1)+$samples, 1); | ||
| 351 | } | ||
| 352 | } else { | ||
| 353 | # fractional bytes (bps < 8) possible to have not 2**N? | ||
| 354 | my $strideBits = $bps*($samples+1); | ||
| 355 | my $inbits = unpack('B*', $inbuf); # bits from inbuf string | ||
| 356 | my $outbits = ''; # bits to outbuf string (starts empty) | ||
| 357 | my $outbits_a = ''; # build alpha string (starts empty) | ||
| 358 | my $index = 0; | ||
| 359 | for my $row (0 .. $h-1) { | ||
| 360 | my $rowbuf = ''; | ||
| 361 | my $rowbuf_a = ''; | ||
| 362 | for my $column (0 .. $w-1) { | ||
| 363 | $rowbuf .= substr($inbits, $index, $samples*$bps); | ||
| 364 | $index += $samples*$bps; | ||
| 365 | $rowbuf_a .= substr($inbits, $index, $bps); | ||
| 366 | $index += $bps; | ||
| 367 | } | ||
| 368 | |||
| 369 | # padding for input could be different from output, e.g. width = 4 | ||
| 370 | # requires no padding on input, but 4 on output. | ||
| 371 | $index += $w*$samples*($bps+1) % 8; | ||
| 372 | |||
| 373 | # given that bilevel images with a width that is not divisible by 8 | ||
| 374 | # are padded to make a whole number of bytes per row, the padding | ||
| 375 | # must be adjusted when deinterleaving the alpha layer. | ||
| 376 | $outbits .= $rowbuf . pad_buffer($rowbuf, $samples, $bps); | ||
| 377 | $outbits_a .= $rowbuf_a . pad_buffer($rowbuf_a, 1, $bps); | ||
| 378 | } | ||
| 379 | $outbuf = pack('B*', $outbits); | ||
| 380 | $alpha = pack('B*', $outbits_a); | ||
| 381 | } # end of fractional byte (bits) handling | ||
| 382 | |||
| 383 | ## debug | ||
| 384 | ## upon exit, what is output data row? # TEMP | ||
| 385 | #if ($slice[0]>-1 && $bps==16){ | ||
| 386 | # print "bps==16 output data slice: "; | ||
| 387 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 388 | # my $pixel = substr($outbuf, $i*$samples*2, $samples*2); | ||
| 389 | # my @pixelbytes = split //, $pixel; | ||
| 390 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 391 | # print " "; | ||
| 392 | # } | ||
| 393 | # print "\n"; | ||
| 394 | #} | ||
| 395 | #if ($slice[0]>-1 && $bps==8){ | ||
| 396 | # print "bps==8 output data slice: "; | ||
| 397 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 398 | # my $pixel = substr($outbuf, $i*$samples, $samples); | ||
| 399 | # my @pixelbytes = split //, $pixel; | ||
| 400 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 401 | # print " "; | ||
| 402 | # } | ||
| 403 | # print "\n"; | ||
| 404 | #} | ||
| 405 | ## upon exit, what is output alpha row? # TEMP | ||
| 406 | #if ($slice[0]>-1 && $bps==16){ | ||
| 407 | # print "bps==16 output alpha slice: "; | ||
| 408 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 409 | # my $pixel = substr($alpha, $i*2, 2); | ||
| 410 | # my @pixelbytes = split //, $pixel; | ||
| 411 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 412 | # print " "; | ||
| 413 | # } | ||
| 414 | # print "\n"; | ||
| 415 | #} | ||
| 416 | #if ($slice[0]>-1 && $bps==8){ | ||
| 417 | # print "bps==8 output alpha slice: "; | ||
| 418 | # for (my $i=$slice[0]; $i<$slice[1]; $i++){ | ||
| 419 | # my $pixel = substr($alpha, $i, 1); | ||
| 420 | # my @pixelbytes = split //, $pixel; | ||
| 421 | # foreach (@pixelbytes) {printf("%02X", ord($_));} | ||
| 422 | # print " "; | ||
| 423 | # } | ||
| 424 | # print "\n"; | ||
| 425 | #} | ||
| 426 | |||
| 427 | return ($outbuf, $alpha); | ||
| 428 | } # end of split_alpha() | ||
| 429 | |||
| 430 | sub pad_buffer { | ||
| 431 | my ($buf, $samples, $bps) = @_; | ||
| 432 | my $padbuf = ''; | ||
| 433 | my $pad = length($buf) % 8; | ||
| 434 | if ($pad) { | ||
| 435 | $pad = 8 - $pad; | ||
| 436 | } | ||
| 437 | for (0..$samples*$bps*$pad-1) { | ||
| 438 | $padbuf .= '0'; | ||
| 439 | } | ||
| 440 | return $padbuf; | ||
| 441 | } | ||
| 442 | |||
| 443 | # bps = width of a sample in bits, samples 1 (G) or 3 (RGB) | ||
| 444 | # return updated buffer WARNING: not tested! | ||
| 445 | sub descale { | ||
| 446 | my ($inbuf, $samples, $bps, $alpha, $count) = @_; | ||
| 447 | my $outbuf = ''; | ||
| 448 | if ($bps == 1) { | ||
| 449 | # 1 bps no effect | ||
| 450 | $outbuf = $inbuf; | ||
| 451 | return $outbuf; | ||
| 452 | } | ||
| 453 | # 1. assuming alpha is 0.0 fully transparent to 1.0 fully opaque | ||
| 454 | # 2. sample has already been multiplied by alpha (0 if fully transparent) | ||
| 455 | # 3. if alpha is 0, leave sample as 0. otherwise... | ||
| 456 | # 4. convert sample and alpha to decimal 0.0..1.0 | ||
| 457 | # 5. sample = sample/alpha | ||
| 458 | # 6. round, integerize, and clamp sample to 0..max val range | ||
| 459 | my $maxVal = 2**$bps - 1; | ||
| 460 | my ($pixR, @samplesR, @samplesC, $alphaR); | ||
| 461 | |||
| 462 | # items used for fractional byte (bits) | ||
| 463 | my $strideBits = $bps*$samples; | ||
| 464 | my @inBits = (); # bits from inbuf string | ||
| 465 | my @outBits = (); # bits to outbuf string (starts empty) | ||
| 466 | my @inABits = (); # bits from alpha string | ||
| 467 | my $inByte = 0; # 1 or 3 samples only, not changing alpha values | ||
| 468 | my $outByte = 0; | ||
| 469 | my $inAByte = 0; | ||
| 470 | |||
| 471 | for (my $pix = 0; $pix < $count; $pix++) { | ||
| 472 | if ($bps == 16) { # not sure if TIFF does 16bps | ||
| 473 | @samplesC = split //, substr($alpha, $pix, 2); | ||
| 474 | $alphaR = (ord($samplesC[0])*256 + ord($samplesC[1]))*1.0/$maxVal; | ||
| 475 | if ($alphaR > 0.0) { | ||
| 476 | @samplesC = split //, substr($inbuf, $pix*$samples*2, $samples*2); | ||
| 477 | for (my $i=0; $i<$samples; $i++) { | ||
| 478 | $pixR = (ord($samplesC[2*$i])*256+ord($samplesC[2*$i+1]))*1.0/$maxVal; | ||
| 479 | $pixR /= $alphaR; | ||
| 480 | $pixR = int($pixR * $maxVal); | ||
| 481 | $outbuf .= chr($pixR>>8); | ||
| 482 | $outbuf .= chr($pixR%256); | ||
| 483 | } | ||
| 484 | } else { | ||
| 485 | # alpha is 0 for this pixel, so just use original value | ||
| 486 | $outbuf .= substr($inbuf, $pix*$samples*2, $samples*2); | ||
| 487 | } | ||
| 488 | } elsif ($bps == 8) { | ||
| 489 | $alphaR = ord(substr($alpha, $pix, 1))*1.0/$maxVal; | ||
| 490 | if ($alphaR > 0.0) { | ||
| 491 | @samplesC = split //, substr($inbuf, $pix*$samples, $samples); | ||
| 492 | foreach (@samplesC) { | ||
| 493 | $pixR = ord($_)*1.0/$maxVal; | ||
| 494 | $pixR /= $alphaR; | ||
| 495 | $outbuf .= chr(int($pixR * $maxVal)); | ||
| 496 | } | ||
| 497 | } else { | ||
| 498 | # alpha is 0 for this pixel, so just use original value | ||
| 499 | $outbuf .= substr($inbuf, $pix*$samples, $samples); | ||
| 500 | } | ||
| 501 | } else { # 1 < $bps < 8. $pix-th pixel, $samples 1 or 3 | ||
| 502 | # fractions of a byte per sample | ||
| 503 | # pix-th pixel is next 2 or more bits in inBits | ||
| 504 | |||
| 505 | # build up enough bits in inBits to get full pixel data | ||
| 506 | while (scalar(@inBits) < $strideBits) { | ||
| 507 | push @inBits, split(//, unpack('B8', substr($inbuf, $inByte++, 1))); | ||
| 508 | } | ||
| 509 | my @Bits = (); | ||
| 510 | for (my $i=0; $i<$samples; $i++) { | ||
| 511 | push @Bits, [splice(@inBits, 0, $bps)]; | ||
| 512 | } | ||
| 513 | # now have enough bits in Bits array for recalculating or | ||
| 514 | # adding to output buffer (if skip due to alpha) | ||
| 515 | |||
| 516 | # build up enough bits in inABits to get next alpha | ||
| 517 | while (scalar(@inABits) < $bps) { | ||
| 518 | push @inABits, split(//, unpack('B8', substr($alpha, $inAByte++, 1))); | ||
| 519 | } | ||
| 520 | # now have enough bits in inABits array for calculating alpha | ||
| 521 | my @ABits = splice(@inABits, 0, $bps); | ||
| 522 | $alphaR = ba2ui(@ABits)*1.0/$maxVal; | ||
| 523 | |||
| 524 | # calculate alpha, and if > 0, make real 0.0-1.0... | ||
| 525 | if ($alphaR > 0.0) { | ||
| 526 | # ...turn sample(s) into reals 0.0-1.0, divide by alpha | ||
| 527 | # turn samples back into ints, then bits to add to outBits | ||
| 528 | for (my $i=0; $i<$samples; $i++) { | ||
| 529 | $pixR = ba2ui(@{ $Bits[$i] })*1.0/$maxVal; | ||
| 530 | $pixR /= $alphaR; | ||
| 531 | $Bits[$i] = ui2ba(int($pixR*$maxVal), $bps); | ||
| 532 | } | ||
| 533 | } | ||
| 534 | |||
| 535 | # @Bits returned to outBits, whether original or recalculated | ||
| 536 | for (my $i=0; $i<$samples; $i++) { | ||
| 537 | push @outBits, @{ $Bits[$i] }; | ||
| 538 | } | ||
| 539 | |||
| 540 | # do we have at least one full byte to output to outbuf? | ||
| 541 | while (scalar(@outBits) >= 8) { | ||
| 542 | substr($outbuf, $outByte++, 1) = pack('B8', join('', splice(@outBits, 0, 8))); | ||
| 543 | } | ||
| 544 | # there may be leftover bits (for next pixel) in inBits | ||
| 545 | # outBits may also have partial content yet to write | ||
| 546 | |||
| 547 | } # end of fractional byte section | ||
| 548 | } # loop through pixels ($pix) | ||
| 549 | |||
| 550 | # fractional bytes, anything waiting to be written out? | ||
| 551 | # @outBits should be empty for bps=8/16, may be empty otherwise | ||
| 552 | if (scalar(@outBits)) { | ||
| 553 | # pad out to 8 bits in length (should be no more than 7) | ||
| 554 | while (scalar(@outBits) < 8) { | ||
| 555 | push @outBits, 0; | ||
| 556 | } | ||
| 557 | substr($outbuf, $outByte++, 1) = pack('B8', join('', @outBits)); | ||
| 558 | } | ||
| 559 | |||
| 560 | # not changing Alpha array at all | ||
| 561 | return $outbuf; | ||
| 562 | } # end of descale() | ||
| 563 | |||
| 564 | # binary bit stream array to unsigned integer | ||
| 565 | sub ba2ui { | ||
| 566 | my @inArray = @_; | ||
| 567 | |||
| 568 | my $value = 0; | ||
| 569 | foreach (@inArray) { | ||
| 570 | $value = 2*$value + $_; | ||
| 571 | } | ||
| 572 | return $value; | ||
| 573 | } | ||
| 574 | |||
| 575 | # unsigned integer to binary bit stream array | ||
| 576 | sub ui2ba { | ||
| 577 | my ($inVal, $maxBits) = @_; | ||
| 578 | |||
| 579 | my $maxVal = 2**$maxBits-1; # not to exceed this value | ||
| 580 | if ($inVal > $maxVal) { $inVal = $maxVal; } | ||
| 581 | if ($inVal < 0) { $inVal = 0; } | ||
| 582 | |||
| 583 | my @array = (); | ||
| 584 | my $bit; | ||
| 585 | foreach (1 .. $maxBits) { | ||
| 586 | $bit = $inVal%2; | ||
| 587 | unshift @array, $bit; | ||
| 588 | $inVal >>= 1; | ||
| 589 | } | ||
| 590 | |||
| 591 | return @array; | ||
| 592 | } | ||
| 593 | |||
| 594 | sub handle_ccitt { | ||
| 595 | my ($self, $pdf, $tif, %opts) = @_; | ||
| 596 | my ($stripcount); | ||
| 597 | |||
| 598 | $self->{' nofilt'} = 1; | ||
| 599 | $self->{'Filter'} = PDFArray(PDFName('CCITTFaxDecode')); | ||
| 600 | my $decode = PDFDict(); | ||
| 601 | $self->{'DecodeParms'} = PDFArray($decode); | ||
| 602 | # DecodeParms.K 0 if G3 or there are G3 options with bit 0 set, -1 for G4 | ||
| 603 | $decode->{'K'} = ($tif->{'ccitt'} == 4 || | ||
| 604 | (defined $tif->{'g3Options'} && $tif->{'g3Options'} & 0x1))? PDFNum(-1): PDFNum(0); | ||
| 605 | $decode->{'Columns'} = PDFNum($tif->{'imageWidth'}); | ||
| 606 | $decode->{'Rows'} = PDFNum($tif->{'imageHeight'}); | ||
| 607 | $decode->{'BlackIs1'} = PDFBool($tif->{'whiteIsZero'} == 1? 1: 0); | ||
| 608 | $decode->{'DamagedRowsBeforeError'} = PDFNum(100); | ||
| 609 | # all CCITT Fax need to flip black/white | ||
| 610 | $self->{'Decode'} = PDFArray(PDFNum(1), PDFNum(0)); | ||
| 611 | |||
| 612 | # g3Options bit 0 = 0 for 1-Dimensional, = 1 for 2-Dimensional MR | ||
| 613 | # aka T4Options bit 1 = 0 (compressed data only) | ||
| 614 | # bit 2 = 0 non-byte-aligned EOLs, = 1 byte-aligned EOLs | ||
| 615 | # g4Options bit 0 = 0 MMR 2-D compression | ||
| 616 | # aka T6Options bit 1 = 0 (compressed data only) | ||
| 617 | # aka Group4Options | ||
| 618 | if (defined($tif->{'g3Options'}) && ($tif->{'g3Options'} & 0x4)) { | ||
| 619 | $decode->{'EndOfLine'} = PDFBool(1); | ||
| 620 | $decode->{'EncodedByteAlign'} = PDFBool(1); | ||
| 621 | } | ||
| 622 | # TBD currently nothing to look at for g4Options | ||
| 623 | |||
| 624 | if (ref($tif->{'imageOffset'})) { | ||
| 625 | die "Chunked CCITT G3/G4 TIFF not supported."; | ||
| 626 | } else { | ||
| 627 | $stripcount = $tif->{'object'}->NumberOfStrips(); | ||
| 628 | for my $i (0 .. $stripcount - 1) { | ||
| 629 | $self->{' stream'} .= $tif->{'object'}->ReadRawStrip($i, -1); | ||
| 630 | } | ||
| 631 | # if bit fill order in data is opposite of PDF spec (Lsb2Msb), need to | ||
| 632 | # swap each byte end-for-end: x01->x80, x02->x40, x03->xC0, etc. | ||
| 633 | # | ||
| 634 | # a 256-entry lookup table could probably do just as well and build | ||
| 635 | # up the replacement string rather than constantly substr'ing. | ||
| 636 | if ($tif->{'fillOrder'} == 2) { # Lsb first, PDF is Msb | ||
| 637 | my ($oldByte, $newByte); | ||
| 638 | for my $j ( 0 .. length($self->{' stream'}) ) { | ||
| 639 | # swapping j-th byte of stream | ||
| 640 | $oldByte = ord(substr($self->{' stream'}, $j, 1)); | ||
| 641 | if ($oldByte == 0 || $oldByte == 255) { next; } | ||
| 642 | $newByte = 0; | ||
| 643 | if ($oldByte & 0x01) { $newByte |= 0x80; } | ||
| 644 | if ($oldByte & 0x02) { $newByte |= 0x40; } | ||
| 645 | if ($oldByte & 0x04) { $newByte |= 0x20; } | ||
| 646 | if ($oldByte & 0x08) { $newByte |= 0x10; } | ||
| 647 | if ($oldByte & 0x10) { $newByte |= 0x08; } | ||
| 648 | if ($oldByte & 0x20) { $newByte |= 0x04; } | ||
| 649 | if ($oldByte & 0x40) { $newByte |= 0x02; } | ||
| 650 | if ($oldByte & 0x80) { $newByte |= 0x01; } | ||
| 651 | substr($self->{' stream'}, $j, 1) = chr($newByte); | ||
| 652 | } | ||
| 653 | } | ||
| 654 | } | ||
| 655 | |||
| 656 | return $self; | ||
| 657 | } # end of handle_ccitt() | ||
| 658 | |||
| 659 | sub handle_lzw { | ||
| 660 | my ($self, $pdf, $tif, %opts) = @_; | ||
| 661 | |||
| 662 | # colorspace DeviceGray or DeviceRGB already set in read_tiff() | ||
| 663 | # bits_per_component 1 2 4 8 16? already set in read_tiff() | ||
| 664 | $self->{' nofilt'} = 1; | ||
| 665 | $self->{'Filter'} = PDFArray(PDFName('LZWDecode')); | ||
| 666 | my $dict = PDFDict(); | ||
| 667 | $self->{'DecodeParms'} = PDFArray($dict); | ||
| 668 | $dict->{'Columns'} = PDFNum($tif->{'imageWidth'}); | ||
| 669 | $dict->{'Rows'} = PDFNum($tif->{'imageHeight'}); | ||
| 670 | # colorspace DeviceGray or DeviceRGB already set in read_tiff() | ||
| 671 | # bits_per_component 1 2 4 8 16? already set in read_tiff() | ||
| 672 | $dict->{'BitsPerComponent'} = PDFNum($tif->{'bitsPerSample'}); | ||
| 673 | $dict->{'Colors'} = PDFNum($tif->{'colorSpace'} eq 'DeviceGray'?1 :3); | ||
| 674 | if (defined $tif->{'Predictor'} and $tif->{'Predictor'} > 1) { | ||
| 675 | $dict->{'Predictor'} = PDFNum($tif->{'Predictor'}); | ||
| 676 | } | ||
| 677 | |||
| 678 | # have to decode in case we have alpha to split out | ||
| 679 | $self->decode_all_strips($tif); | ||
| 680 | my $alpha = $self->handle_alpha($pdf, $tif, %opts); | ||
| 681 | |||
| 682 | # bilevel must be flipped | ||
| 683 | if ($alpha and $tif->{'bitsPerSample'} == 1) { | ||
| 684 | $self->{'Decode'} = PDFArray(PDFNum(1), PDFNum(0)); | ||
| 685 | } | ||
| 686 | |||
| 687 | my $filter = PDF::Builder::Basic::PDF::Filter::LZWDecode->new($dict); | ||
| 688 | $self->{' stream'} = $filter->outfilt($self->{' stream'}); | ||
| 689 | |||
| 690 | if (defined $alpha and defined $alpha->{' stream'}) { # there is transparency? | ||
| 691 | if (length($alpha->{' stream'}) > 32) { | ||
| 692 | my $filter = PDF::Builder::Basic::PDF::Filter::LZWDecode->new(); | ||
| 693 | $alpha->{' stream'} = $filter->outfilt($alpha->{' stream'}); | ||
| 694 | $alpha->filters('LZWDecode'); # tell reader it's compressed... | ||
| 695 | } else { | ||
| 696 | # too short to bother compressing. '/Filter [ /LZWDecode ] ' | ||
| 697 | # takes up 25 bytes all by itself | ||
| 698 | delete $alpha->{Filter}; | ||
| 699 | } | ||
| 700 | $alpha->{' nofilt'} = 1; # ...but writer not to compress on the fly | ||
| 701 | } | ||
| 702 | |||
| 703 | return $self; | ||
| 704 | } # end of handle_lzw() | ||
| 705 | |||
| 706 | sub read_tiff { | ||
| 707 | my ($self, $pdf, $tif, %opts) = @_; | ||
| 708 | |||
| 709 | $self->width($tif->{'imageWidth'}); | ||
| 710 | $self->height($tif->{'imageHeight'}); | ||
| 711 | |||
| 712 | if ($tif->{'colorSpace'} eq 'Indexed') { | ||
| 713 | my $dict = PDFDict(); | ||
| 714 | $pdf->new_obj($dict); | ||
| 715 | $self->colorspace(PDFArray(PDFName($tif->{'colorSpace'}), | ||
| 716 | PDFName('DeviceRGB'), PDFNum(2**$tif->{'bitsPerSample'}-1), $dict)); | ||
| 717 | $dict->{'Filter'} = PDFArray(PDFName('FlateDecode')); | ||
| 718 | my ($red, $green, $blue) = @{$tif->{'colorMap'}}; | ||
| 719 | $dict->{' stream'} = ''; | ||
| 720 | for my $i (0 .. $#{$red}) { | ||
| 721 | $dict->{' stream'} .= pack('C', ($red->[$i]/256)); | ||
| 722 | $dict->{' stream'} .= pack('C', ($green->[$i]/256)); | ||
| 723 | $dict->{' stream'} .= pack('C', ($blue->[$i]/256)); | ||
| 724 | } | ||
| 725 | } else { | ||
| 726 | # DeviceGray or DeviceRGB | ||
| 727 | $self->colorspace($tif->{'colorSpace'}); | ||
| 728 | } | ||
| 729 | |||
| 730 | $self->{'Interpolate'} = PDFBool(1); | ||
| 731 | $self->bits_per_component($tif->{'bitsPerSample'}); | ||
| 732 | |||
| 733 | # swaps 0 and 1 ([0 1] -> [1 0]) in certain cases | ||
| 734 | if (($tif->{'whiteIsZero'}||0) == 1 && | ||
| 735 | ($tif->{'filter'}||'') ne 'CCITTFaxDecode') { | ||
| 736 | $self->{'Decode'} = PDFArray(PDFNum(1), PDFNum(0)); | ||
| 737 | } | ||
| 738 | |||
| 739 | # check filters and handle separately | ||
| 740 | if (defined $tif->{'filter'} and $tif->{'filter'} eq 'CCITTFaxDecode') { | ||
| 741 | $self->handle_ccitt($pdf, $tif, %opts); | ||
| 742 | } elsif (defined $tif->{'filter'} and $tif->{'filter'} eq 'LZWDecode') { | ||
| 743 | $self->handle_lzw($pdf, $tif, %opts); | ||
| 744 | } else { | ||
| 745 | $self->handle_generic($pdf, $tif, %opts); | ||
| 746 | } | ||
| 747 | |||
| 748 | $self->{' tiff'} = $tif; | ||
| 749 | |||
| 750 | return $self; | ||
| 751 | } # end of read_tiff() | ||
| 752 | |||
| 753 | 1; |