/
JPEG.pm
86 lines (74 loc) · 2.51 KB
/
JPEG.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use v6;
use PDF::Content::Image;
# adapted from Perl 5's PDF::API::Resource::XObject::Image::JPEG
class PDF::Content::Image::JPEG
is PDF::Content::Image {
use Native::Packing :Endian;
class Atts does Native::Packing[Network] {
has uint8 $.bit-depth;
has uint16 ($.height, $.width);
has uint8 $.color-channels
}
class BlockHeader does Native::Packing[Network] {
has uint8 ($.ff, $.mark);
has uint16 $.len
}
# work-around for Rakudo RT #131122 - sign handling
has Atts $!atts;
has Bool $!is-dct;
has Str $!encoded;
# work-around for Rakudo RT #131122 - sign handling
sub u8(uint8 $v) { $v }
sub u16(uint16 $v) { $v }
method read($fh = $.source) {
$fh.seek(0, SeekFromBeginning);
my Str $header = $fh.read(2).decode: 'latin-1';
die X::PDF::Image::WrongHeader.new( :type<JPEG>, :$header, :path($fh.path) )
unless $header ~~ "\xFF\xD8";
loop {
my BlockHeader $hdr .= read: $fh;
last if u8($hdr.ff) != 0xFF;
last if u8($hdr.mark) ~~ 0xDA|0xD9; # SOS/EOI
my $len := u16($hdr.len);
last if $len < 2;
last if $fh.eof;
my $buf := $fh.read: $len - 2;
given $hdr.mark -> uint8 $mark {
if 0xC0 <= $mark <= 0xCF
&& $mark !~~ 0xC4|0xC8|0xCC {
$!is-dct = ?( $mark ~~ 0xC0|0xC2);
$!atts .= unpack($buf);
last;
}
}
}
$fh.seek(0, SeekFromBeginning);
$!encoded = $fh.read.decode: "latin-1";
$fh.close;
self;
}
method to-dict {
my %dict = :Type( :name<XObject> ), :Subtype( :name<Image> );
with $!atts {
my Str \color-space = do given .color-channels {
constant @ColorSpaces = [Mu, 'DeviceGray', Mu, 'DeviceRGB', 'DeviceCMYK'];
@ColorSpaces[$_]
// do {
warn "JPEG has unknown color-channel: $_";
'DeviceGray'
}
}
%dict<ColorSpace> = :name(color-space);
%dict<Width> = .width;
%dict<Height> = .height;
%dict<BitsPerComponent> = .bit-depth;
}
else {
die "unable to read JPEG attributes";
}
%dict<Filter> = :name<DCTDecode>
if $!is-dct;
need PDF::COS;
PDF::COS.coerce: :stream{ :%dict, :$!encoded };
}
}