lib/LaTeXML/Post/LaTeXImages.pm untested

filter: Statementstmt 0.0% 0 / 292 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 84 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 572 CC 57 SCAR 56.7
CC
57
Cov
0%
generateImages
702.0
pre_preamble
240.0
new
56.0
CRAP 288.7
1 # /=====================================================================\ #
2 # | LaTeXML::Post::LaTeXImages | #
3 # | Abstract Postprocessor to create images from LaTeX code | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12  
13 package LaTeXML::Post::LaTeXImages;
14 use strict;
15 use warnings;
16 use DB_File;
17 use Config;
18 use LaTeXML::Util::Image;
19 use POSIX qw(ceil);
20 use LaTeXML::Util::Pathname;
21 use File::Temp;
22 use File::Which;
23 use LaTeXML::Post;
24 use base qw(LaTeXML::Post::Processor);
25  
26 #======================================================================
27  
28 # Other silly constants that might want changing?
29 ##our $TMP = '/tmp';
30 our $LATEXCMD = 'latex'; #(or elatex) [ CONFIGURABLE? Encoded in PI?]
31  
32 # The purpose of this module is to convert TeX fragments into png (or similar),
33 # typically via dvi and other intermediate formats.
34 # LaTeX converts the TeX stuff to dvi;
35 # dvips converts the dvi to eps, and ImageMagick can convert the eps to png;
36 # OR dvipng can convert the dvi to png MUCH quicker... if it's available.
37  
38 # Options:
39 # source : (dir)
40 # magnification : typically something like 1.33333, but you may want bigger
41 # maxwidth : maximum page width, in pixels (whenever line breaking is possible)
42 # DPI : assumed DPI for the target medium (default 100)
43 # background : color of background (for anti-aliasing, since it is made transparent)
44 # imagetype : typically 'png' or 'gif'.
45 sub new {
46 my ($class, %options) = @_;
47 my $self = $class->SUPER::new(%options);
48 $$self{magnification} = $options{magnification} || 1.33333;
49 $$self{maxwidth} = $options{maxwidth} || 800;
50 $$self{DPI} = $options{DPI} || 100;
51 $$self{background} = $options{background} || "#FFFFFF";
52 $$self{imagetype} = $options{imagetype} || 'png';
53  
54 # Parameters for separating the clipping box from the
55 # desired padding between image edge and "ink"
56 $$self{padding} = $options{padding} || 2; # pixels
57 # amount of extra space (+padding) to put between object & rules for clipping
58 $$self{clippingfudge} = 3; # px
59 $$self{clippingrule} = 0.90; # pixels (< 1 to avoid antialiasing..?)
60  
61 # Sanity check of dvi processing...
62 # If trying to create svg...
63 if (($$self{imagetype} eq 'svg') && (!defined $options{use_dvisvgm}) && which('dvisvgm')) {
64 $$self{use_dvisvgm} = 1; }
65 elsif ($$self{use_dvisvgm} && (($$self{imagetype} ne 'svg') || !which('dvisvgm'))) {
66 $$self{use_dvisvgm} = 0; } # but disable if inappropriate or unavailable
67 # We'll use dvipng (MUCH faster) if requested or not forbidden & available.
68 # But be careful: it can't handle much postscript, so better NOT for graphics!
69 if (($$self{imagetype} eq 'png') && (!defined $options{use_dvipng}) && which('dvipng')) {
70 $$self{use_dvipng} = 1; }
71 elsif ($$self{use_dvipng} && (($$self{imagetype} ne 'png') || !which('dvipng'))) {
72 $$self{use_dvipng} = 0; } # but disable if inappropriate or unavailable.
73  
74 # Parameterize according to the selected dvi-to-whatever processor.
75 my $mag = int($$self{magnification} * 1000);
76 my $dpi = int($$self{DPI} * $$self{magnification});
77 # Unfortunately, each command has incompatible -o option to name the output file.
78 # Note that the formatting char used, '%', has to be doubled on Windows!!
79 # Maybe that's only true when it looks like an environment variable?
80 # Ie. %variable% ?
81 # my $fmt = ($^O eq 'MSWin32' ? '%%' : '%');
82 my $fmt = '%';
83 if ($$self{use_dvisvgm}) {
84 ## $$self{dvicmd} = "dvisvgm --page=1- --bbox=min --mag=$mag -o imgx-${fmt}p";
85 # dvisvgm currently creates glyph descriptions w/ unicode attribute having the wrong codepoint
86 # firefox, chromium use this codepoint instead of the glyph "drawing"
87 # a later version of dvisvgm should do better at synthesizing the unicode?
88 # but for now, we'll use --no-fonts, which creates glyph drawings rather than "glyphs"
89 # Also, increase the bounding box from min by 1pt
90 $$self{dvicmd} = "dvisvgm --page=1- --bbox=1pt --scale=$$self{magnification} --no-fonts -o imgx-${fmt}3p";
91 $$self{dvicmd_output_name} = 'imgx-%03d.svg';
92 $$self{dvicmd_output_type} = 'svg';
93 $$self{frame_output} = 0; }
94 elsif ($$self{use_dvipng}) {
95 $$self{dvicmd} = "dvipng -bg Transparent -T tight -q -D$dpi -o imgx-${fmt}03d.png";
96 $$self{dvicmd_output_name} = 'imgx-%03d.png';
97 $$self{dvicmd_output_type} = 'png32';
98 $$self{frame_output} = 1; }
99 else {
100 # Useful DVIPS options:
101 # -q : run quietly
102 # -x# : magnification * 1000
103 # -S1 -i : make a separate file for each `section' consisting of a single page.
104 # QUESTION: dvips' naming scheme allows for 999 pages... what happens at 1000?
105 # -E : crop each page close to the `ink'.
106 # -j0 : don't subset fonts; silly really, but some font tests are making problems!
107 $$self{dvicmd} = "dvips -q -S1 -i -E -j0 -x$mag -o imgx";
108 $$self{dvicmd_output_name} = 'imgx%03d';
109 $$self{dvicmd_output_type} = 'eps';
110 $$self{frame_output} = 1; }
111 return $self; }
112  
113 #**********************************************************************
114 # Check whether this processor actually has the resources it needs to process.
115 # I don't know if there's a general API implied here;
116 # It could, conceivably be use in planning post processing?
117 # But generally, before signalling an error, you'd want to know that the processor
118 # is even needed.
119 # This test is called once we know that, from within
120 #
121 # At any rate: To process LaTeX snippets into images, we will need
122 # * latex (or related) from a TeX installation
123 # * Image::Magick (or similar) [see LaTeXML::Util::Image]
124 sub canProcess {
125 my ($self) = @_;
126 # Check if we have Image::Magick (or similar)
127 if (!image_can_image()) {
128 Error('expected', 'Image::Magick', undef,
129 "No available image processing module found; Skipping.",
130 "Please install one of: " . join(',', image_classes()));
131 return; }
132 # AND check if we have an approriprate latex!!!
133 if (($LATEXCMD =~ /^(\S+)/) && !which($1)) { # does the command seem to be available?
134 Error('expected', $LATEXCMD, undef,
135 "No latex command ($LATEXCMD) found; Skipping.",
136 "Please install TeX to generate images from LaTeX");
137 return; }
138 return 1; }
139  
140 #**********************************************************************
141 # Methods that must be defined;
142  
143 # This is an abstract class; concrete classes must select the nodes to process.
144 # We'll still need to use $proc->extractTeX($doc,$node)
145 # to extract the actual TeX string!
146 sub toProcess {
147 return (); }
148  
149 # $self->extractTeX($doc,$node)=>$texstring;
150 sub extractTeX {
151 return ""; }
152  
153 # $self->format_tex($texstring)
154 sub format_tex {
155 return ""; }
156  
157 # $self->setTeXImage($doc,$node,$imagepath,$width,$height);
158 # This is the default
159 sub setTeXImage {
160 my ($self, $doc, $node, $path, $width, $height, $depth) = @_;
161 $node->setAttribute('imagesrc', pathname_to_url($path));
162 $node->setAttribute('imagewidth', $width);
163 $node->setAttribute('imageheight', $height);
164 $node->setAttribute('imagedepth', $depth) if defined $depth;
165 return; }
166  
167 #======================================================================
168 # Methods that could be wrapped, overridden.
169  
170 # Should be called by extractTeX
171 sub cleanTeX {
172 my ($self, $tex) = @_;
173 return unless defined $tex;
174 my $style = '';
175 # Save any leading style
176 if ($tex =~ s/^\s*(\\displaystyle|\\textstyle|\\scriptstyle|\\scriptscriptstyle)\s*//) {
177 $style = $1; }
178 $tex =~ s/^(?:\\\s*,|\\!\s*|\\>\s*|\\;\s*|\\:\s*|\\ \s*|\\\/\s*)*//; # Trim leading spacing (especially negative!)
179 $tex =~ s/(?:\\\s*,|\\!\s*|\\>\s*|\\;\s*|\\:\s*|\\ \s*|\\\/\s*)*$//; # and trailing spacing
180 # Strip comments, but watchout for \% (or more exactly, an ODD number of \)
181 $tex =~ s/(?<!\\)((?:\\\\)*)\%[^\n]*\n/$1/gs;
182 $tex = $style . ' ' . $tex if $style; # Put back the style, if any
183 return $tex; }
184  
185 #**********************************************************************
186  
187 #**********************************************************************
188 # Generating & Processing the LaTeX source.
189 #**********************************************************************
190 # Need the destination directory AND (optionally?) a subdir for the images.
191 # both are only used here.
192 # Alternatively, a dest for doc & dest for images ?
193 # What we really need to know is:
194 # (1) where to write the images.
195 # (2) relative path from doc to images.
196  
197 # sub process {
198 # my ($self, $doc, @nodes) = @_;
199 # return $self->generateImages($doc, @nodes); }
200  
201 sub generateImages {
202 my ($self, $doc, @nodes) = @_;
203  
204 my $jobname = "ltxmlimg";
205 my $orig_cwd = pathname_cwd();
206 my $sep = $Config::Config{path_sep};
207 my %table = ();
208  
209 # === Get the desired nodes, extract the set of unique tex strings,
210 # noting which need processing.
211 # Note that if desiredResourcePathname is implemented, we might get
212 # several desired names for the same chunk of tex!!!
213 my ($ntotal, $nuniq) = (0, 0);
214 foreach my $node (@nodes) {
215 my $tex = $self->extractTeX($doc, $node);
216 next if !(defined $tex) || ($tex =~ /^\s*$/);
217 $ntotal++;
218  
219 # Ideally, $dest is relative to document..
220 my $dest = $self->desiredResourcePathname($doc, $node, undef, $$self{imagetype});
221 # my $key = (ref $self) . ":" . $tex . ($dest ? ":$dest" : '');
222 my $key = (ref $self) . ':' . $$self{imagetype} . ':' . $tex;
223 my $entry = $table{$key};
224 if (!$entry) {
225 $nuniq++;
226 $entry = $table{$key} = { tex => $tex, key => $key, nodes => [], dest => [] }; }
227 # Why do I need to make things so complicated?!?!
228 # It may be desired that a particular image gets a specific name.
229 # AND, the same TeX may get different names, or some with & without names!!
230 if ($dest && (!grep { $dest eq $_ } @{ $$entry{dest} })) {
231 push(@{ $$entry{dest} }, $dest); }
232 push(@{ $$entry{nodes} }, $node); }
233  
234 return $doc unless $nuniq; # No strings to process!
235  
236 return unless $self->canProcess;
237  
238 # === Check which objects still need processing.
239 my $destdir = $doc->getDestinationDirectory;
240 my @pending = ();
241 foreach my $key (sort keys %table) {
242 my $store = $doc->cacheLookup($key);
243 if ($store && ($store =~ /^(.*);(\d+);(\d+);(\d+)$/)) {
244 next if -f pathname_absolute($1, $destdir); }
245 push(@pending, $table{$key}); }
246  
247 Debug("LaTeXImages: $nuniq unique; " . scalar(@pending) . " new") if $LaTeXML::DEBUG{images};
248 if (@pending) { # if any images need processing
249 # Create working directory; note TMPDIR attempts to put it in standard place (like /tmp/)
250 File::Temp->safe_level(File::Temp::MEDIUM);
251 my $workdir = File::Temp->newdir("LaTeXMLXXXXXX", TMPDIR => 1);
252 # Obtain the search paths
253 my @searchpaths = $doc->getSearchPaths;
254 my $installation_path = pathname_installation();
255 # === Generate the LaTeX file.
256 my $texfile = pathname_make(dir => $workdir, name => $jobname, type => 'tex');
257 my $TEX;
258 if (!open($TEX, '>', $texfile)) {
259 Error('I/O', $texfile, undef, "Cant write to '$texfile'", "Response was: $!");
260 return $doc; }
261 my ($pre_preamble, $add_to_body) = $self->pre_preamble($doc);
262 binmode $TEX, ':encoding(UTF-8)';
263 print $TEX $pre_preamble if $pre_preamble;
264 print $TEX "\\makeatletter\n";
265 print $TEX $self->preamble($doc) . "\n";
266 print $TEX "\\makeatother\n";
267 print $TEX "\\begin{document}\n";
268 print $TEX $add_to_body if $add_to_body;
269  
270 foreach my $entry (@pending) {
271 ## print TEX "\\fbox{$$entry{tex}}\\clearpage\n"; }
272 print $TEX "$$entry{tex}\\clearpage\n"; }
273 print $TEX "\\end{document}\n";
274 close($TEX);
275  
276 # === Run LaTeX on the file.
277 # (keep the command simple so it works in Windows)
278 pathname_chdir($workdir);
279 my $ltxcommand = "$LATEXCMD $jobname > $jobname.ltxoutput";
280 my $ltxerr;
281 {
282 local $ENV{TEXINPUTS} = join($sep, '.', @searchpaths,
283 pathname_concat($installation_path, 'texmf'),
284 ($ENV{TEXINPUTS} || $sep));
285 $ltxerr = system($ltxcommand);
286 }
287 pathname_chdir($orig_cwd);
288  
289 # Sometimes latex returns non-zero code, even though it apparently succeeded.
290 # And sometimes it doesn't produce a dvi, even with 0 return code?
291 if (($ltxerr != 0) || (!-f "$workdir/$jobname.dvi")) {
292 $workdir->unlink_on_destroy(0) if $LaTeXML::DEBUG{images}; # Preserve junk
293 Error('shell', $LATEXCMD, undef,
294 "LaTeX command '$ltxcommand' failed",
295 ($ltxerr == 0 ? "No dvi file generated" : "returned code $ltxerr (!= 0): $@"),
296 ($LaTeXML::DEBUG{images}
297 ? "See $workdir/$jobname.log"
298 : "Re-run with --debug=images to see TeX log"));
299 return $doc; }
300 ### $workdir->unlink_on_destroy(0) if $LaTeXML::DEBUG{images}; # preserve ALL junk!?!?!
301  
302 # Extract dimensions (width x height+depth) from each image from log file.
303 my @dimensions = ();
304 my $LOG;
305 if (open($LOG, '<', "$workdir/$jobname.log")) {
306 while (<$LOG>) {
307 if (/^\s*LXIMAGE\s*(\d+)\s*=\s*([\+\-\d\.]+)pt\s*x\s*([\+\-\d\.]+)pt\s*\+\s*([\+\-\d\.]+)pt\s*$/) {
308 $dimensions[$1] = [$2, $3, $4]; } }
309 close($LOG); }
310 else {
311 Warn('expected', 'dimensions', undef,
312 "Couldn't read log file $workdir/$jobname.log to extract image dimensions",
313 "Response was: $!"); }
314  
315 # === Run dvicmd to extract individual png|postscript files.
316 pathname_chdir($workdir);
317 my $dvicommand = "$$self{dvicmd} $jobname.dvi > $jobname.dvioutput";
318 my $dvierr;
319 {
320 local $ENV{TEXINPUTS} = join($sep, '.', @searchpaths,
321 pathname_concat($installation_path, 'texmf'),
322 ($ENV{TEXINPUTS} || $sep));
323 $dvierr = system($dvicommand);
324 }
325 pathname_chdir($orig_cwd);
326  
327 if ($dvierr != 0) {
328 Error('shell', $$self{dvicmd}, undef,
329 "Shell command '$dvicommand' (for dvi conversion) failed (see $workdir for clues)",
330 "Response was: $!");
331 return $doc; }
332 # === Convert each image to appropriate type and put in place.
333 my $pixels_per_pt = $$self{magnification} * $$self{DPI} / 72.27;
334 my ($index, $ndigits) = (0, 1 + int(log($doc->cacheLookup((ref $self) . ':_max_image_') || 1) / log(10)));
335 foreach my $entry (@pending) {
336 my $src = "$workdir/" . sprintf($$self{dvicmd_output_name}, ++$index);
337 if (-f $src) {
338 my @dests = @{ $$entry{dest} };
339 push(@dests, $self->generateResourcePathname($doc, $$entry{nodes}[0], undef, $$self{imagetype}))
340 unless @dests;
341 foreach my $dest (@dests) {
342 my $absdest = $doc->checkDestination($dest);
343 my ($ww, $hh, $dd) = map { $_ * $pixels_per_pt } @{ $dimensions[$index] };
344 my ($w, $h);
345 if ($$self{frame_output}) { # If framed, trim the frame
346 ($w, $h) = $self->convert_image($doc, $src, $absdest);
347 next unless defined $w && defined $h; }
348 else {
349 pathname_copy($src, $absdest);
350 $w = int($ww + 0.5); $h = int($hh + $dd + 0.5); }
351 my $d = int(0.5 + ($dd || 0) + $$self{padding});
352 if ((($w == 1) && ($ww > 1)) || (($h == 1) && ($hh > 1))) {
353 Warn('expected', 'image', undef, "Image for '$$entry{tex}' was cropped to nothing!"); }
354 $doc->cacheStore($$entry{key}, "$dest;$w;$h;$d"); }
355 }
356 else {
357 Warn('expected', 'image', undef, "Missing image '$src'; See $workdir/$jobname.log"); } } }
358  
359 # Finally, modify the original document to record the associated images.
360 foreach my $entry (values %table) {
361 next unless ($doc->cacheLookup($$entry{key}) || '') =~ /^(.*);(\d+);(\d+);(\d+)$/;
362 my ($image, $width, $height, $depth) = ($1, $2, $3, $4);
363 # Ideally, $image is already relative, but if not, make relative to document
364 my $reldest = pathname_relative($image, $doc->getDestinationDirectory);
365 foreach my $node (@{ $$entry{nodes} }) {
366 $self->setTeXImage($doc, $node, $reldest, $width, $height, $depth); } }
367  
368 $doc->closeCache; # If opened.
369 return $doc; }
370  
371 #======================================================================
372 # Generating & Processing the LaTeX source.
373 #======================================================================
374  
375 sub pre_preamble {
376 my ($self, $doc) = @_;
377 my @classdata = $self->find_documentclass_and_packages($doc);
378 my ($class, $class_options, $oldstyle) = @{ shift(@classdata) };
379 $class_options = "[$class_options]" if $class_options && ($class_options !~ /^\[.*\]$/);
380 $class_options = '' unless defined $class_options;
381 my $documentcommand = ($oldstyle ? "\\documentstyle" : "\\documentclass");
382 my $packages = '';
383 my $dest = $doc->getDestination;
384 my $description = ($dest ? "% Destination $dest" : "");
385 my $pts_per_pixel = 72.27 / $$self{DPI} / $$self{magnification};
386 my %loaded_check = ();
387  
388 foreach my $pkgdata (@classdata) {
389 my ($package, $package_options) = @$pkgdata;
390 next if $loaded_check{$package};
391 $loaded_check{$package} = 1;
392 if ($oldstyle) {
393 next if $package =~ /latexml/; # some packages are incompatible.
394 $packages .= "\\RequirePackage{$package}\n"; }
395 else {
396 if ($package eq 'english') {
397 $packages .= "\\usepackage[english]{babel}\n"; }
398 else {
399 $package_options = "[$package_options]" if $package_options && ($package_options !~ /^\[.*\]$/);
400 $packages .= "\\usepackage$package_options\{$package}\n"; } } }
401  
402 my $w = ceil($$self{maxwidth} * $pts_per_pixel); # Page Width in points.
403 my $gap = ($$self{padding} + $$self{clippingfudge}) * $pts_per_pixel;
404 my $th = ($$self{frame_output}
405 ? $$self{clippingrule} * $pts_per_pixel # clipping box thickness in points.
406 : 0); # NO clipping box!
407 my $preambles = $self->find_preambles($doc);
408 # Some classes are too picky: thanks but no thanks
409 my $result_add_to_body = "\\makeatletter\\thispagestyle{empty}\\pagestyle{empty}\n";
410 # neutralize caption macros
411 $result_add_to_body .= "\\let\\\@\@toccaption\\\@gobble\n\\let\\\@\@caption\\\@gobble\n"
412 . "\\let\\cite\\\@gobble\n\\def\\\@\@bibref#1#2#3#4{}\n";
413 $result_add_to_body .= "\\renewcommand{\\cite}[2][]{}\n" unless $oldstyle;
414 # class-specific conditions:
415 if ($class =~ /^JHEP$/i) {
416 $class = 'article'; }
417 elsif ($class =~ /revtex/) {
418 # Careful with revtex4
419 $result_add_to_body .= "\\\@ifundefined{\@author\@def}{\\author{}}{}\n"; }
420 # when are the empty defaults needed?
421 if ($class ne 'article') {
422 $result_add_to_body .= "\\title{}\\date{}\n"; }
423 $result_add_to_body .= "\\makeatother\n";
424  
425 my $result_preamble = <<"EOPreamble";
426 \\batchmode
427 \\def\\inlatexml{true}
428 $documentcommand$class_options\{$class}
429 $description
430 $packages
431 \\makeatletter
432 \\setlength{\\hoffset}{0pt}\\setlength{\\voffset}{0pt}
433 \\setlength{\\textwidth}{${w}pt}
434 \\newcount\\lxImageNumber\\lxImageNumber=0\\relax
435 \\newbox\\lxImageBox
436 \\newdimen\\lxImageBoxSep
437 \\setlength\\lxImageBoxSep{${gap}\\p\@}
438 \\newdimen\\lxImageBoxRule
439 \\setlength\\lxImageBoxRule{${th}\\p\@}
440 \\def\\lxShowImage{%
441 \\global\\advance\\lxImageNumber1\\relax
442 \\\@tempdima\\wd\\lxImageBox
443 \\advance\\\@tempdima-\\lxImageBoxSep
444 \\advance\\\@tempdima-\\lxImageBoxSep
445 \\typeout{LXIMAGE \\the\\lxImageNumber\\space= \\the\\\@tempdima\\space x \\the\\ht\\lxImageBox\\space + \\the\\dp\\lxImageBox}%
446 \\\@tempdima\\lxImageBoxRule
447 \\advance\\\@tempdima\\lxImageBoxSep
448 \\advance\\\@tempdima\\dp\\lxImageBox
449 \\hbox{%
450 \\lower\\\@tempdima\\hbox{%
451 \\vbox{%
452 \\hrule\\\@height\\lxImageBoxRule%
453 \\hbox{%
454 \\vrule\\\@width\\lxImageBoxRule%
455 \\vbox{%
456 \\vskip\\lxImageBoxSep
457 \\box\\lxImageBox
458 \\vskip\\lxImageBoxSep
459 }%
460 \\vrule\\\@width\\lxImageBoxRule%
461 }%
462 \\hrule\\\@height\\lxImageBoxRule%
463 }%
464 }%
465 }%
466 }%
467 \\def\\lxBeginImage{\\setbox\\lxImageBox\\hbox\\bgroup\\color\@begingroup\\kern\\lxImageBoxSep}
468 \\def\\lxEndImage{\\kern\\lxImageBoxSep\\color\@endgroup\\egroup}
469 $preambles
470 \\makeatother
471 EOPreamble
472  
473 return ($result_preamble, $result_add_to_body); }
474  
475 #======================================================================
476 # Converting the postscript images to gif/png/whatever
477 # Note that properly trimming the clipping box (and keeping the right
478 # padding and dimensions) is harder than it seems!
479 #
480 # Note that this conversion is, indeed, quite slow.
481 # Profiling indicates that virtually ALL the time is taken in ->Read !!
482 # (not the various trimming/shaving).
483 #======================================================================
484  
485 sub convert_image {
486 my ($self, $doc, $src, $dest) = @_;
487 my ($bg, $fg) = ($$self{background}, 'black');
488  
489 my $image = image_object(antialias => 'True', background => $bg, density => $$self{DPI});
490 my $err = $image->Read($$self{dvicmd_output_type} . ':' . $src);
491 if ($err) {
492 Warn('imageprocessing', 'read', undef,
493 "Image conversion failed to read '$src'",
494 "Response was: $err"); return; }
495  
496 my ($ww, $hh) = $image->Get('width', 'height'); # Get final image size
497  
498 # We can't quite rely on the -E option to dvips; there may or may not be white outside the clipbox;
499 # Moreover, rounding can leave (possibly gray) 'tabs' on the clipbox corners.
500 # To be sure, add known white border, and trim away all white AND gray
501 $image->Border(width => 1, height => 1, fill => $bg);
502 $image->Trim(fuzz => '75%'); # Fuzzy, to trim the gray tabs, as well!!
503 $image->Set(fuzz => '0%'); # But, be SURE to RESET fuzz!! (It is NOT an "argument"!!!)
504 # [Also, be CAREFULL of ImageMagick's Floodfill variants, they sometimes go wild]
505  
506 # Finally, shave off the rule & fudge padding.
507 my $fudge = int(0.5 + $$self{clippingfudge} + $$self{clippingrule});
508 $image->Shave(width => $fudge, height => $fudge);
509  
510 my ($w, $h) = $image->Get('width', 'height'); # Get final image size
511 # ImageMagick tries to manage a "virtual" image within the image data,
512 # (whatever that means)
513 # This resets it back to the origin which avoids confusion, all 'round!
514 $image->Set(page => "${w}x${h}+0+0");
515  
516 # Ideally, we'd make the alpha exactly opposite the ink, rather than merely 1 bit
517 # It would seem that this should do it, but currently just seems to turn off alpha completely!!!
518 # $image = $image->Fx(expression=>'(3.0-r+g+b)/3.0', channel=>'alpha');
519 $image->Transparent(color => $bg);
520  
521 Debug("LaTeXImages: Converting $src => $dest ($w x $h)") if $LaTeXML::DEBUG{images};
522 # Workaround bad png detection(?) in ImageMagick 6.6.5 (???)
523 if ($$self{imagetype} eq 'png') {
524 $dest = "png32:$dest"; }
525  
526 $image->Write(filename => $dest);
527 return ($w, $h); }
528  
529 sub DESTROY {
530 if (my $tmpdir = File::Spec->tmpdir()) {
531 if (-d $tmpdir && opendir(my $tmpdir_fh, $tmpdir)) {
532 my @empty_magick = grep { -z $_ } map { "$tmpdir/$_" } readdir($tmpdir_fh);
533 closedir($tmpdir_fh);
534 unlink $_ foreach @empty_magick;
535 } }
536 return; }
537  
538 #======================================================================
539 1;