# How to add illustrations before chapter titles in ConTeXt?

I would like to add some TIFF format illustrations to my document. These have three features, though, which I do not know how to implement:

• These fill the entire page, ignoring margins.
• They appear on the pages immediately before chapter titles. If this if complex to implement, I can just place them manually.
• If the height and width ratio of the illustration does not match the height and width ratio of the page (A4), then the longest dimension should be cropped.

E.g.:

. . ._._._._._. . .
.   |         |   .
.   |         |   .
. x |         | x .
.   |         |   .
.   |         |   .
. . |_._._._._| . .

• Dots represent the graphic.
• Lines represent the page dimensions.
• "x" is where the graphic was cropped, because it is wider than the page.

The page layout looks like this:

 _________ _________
|#########|         |
|#########| ===     |
|#########| ======= |
|#########| ======= |
|#########| ======= |
|#########|____2____|


How can I add graphics to my document in this manner?

-
Do you want the same image before every chapter or one individual image per chapter? –  Marco Jun 6 '12 at 12:21
Do you have a double-sided document? If so, should the image be on the recto or the verso page? –  Aditya Jun 6 '12 at 12:40
It is a different image for each chapter. If needed, I can name them 1.tiff, 2.tiff, etc. It is double-sided. The image should appear on verso pages. –  Village Jun 6 '12 at 13:22
TeX does not handle tiff. So, at the very least, you'll need to pre-process the file to convert it pdf. –  Aditya Jun 6 '12 at 17:33
@Aditya Not quite true. If you have graphicsmagick installed, the conversion takes place on-the-fly, similar to the SVG conversion. See ConTeXt - Dependencies –  Marco Jun 6 '12 at 17:40

Here is a solution that does almost what you request. Warning: Ugly code ahead.

% pretty dummy graphics
\useMPlibrary
[dum]

% fake text
\usemodule
[visual]

\setuppagenumbering
[alternative=doublesided]

\setupbackgrounds
[page]
[background=chapterimages]

\definelayer
[chapterimages]

[chapter]
[before=\setups{s:chapter}]

\newcount\ImageCounter

\definemakeup [chapterimages] [page=left]

\startsetups s:chapter

\startmakeup [chapterimages]

% compute the aspect ratio of the paper and the graphic
\start
\ifcase\ImageCounter
\or
\setbox\scratchbox\vbox{\externalfigure[cow]}
\or
\setbox\scratchbox\vbox{\externalfigure[mill]}
\else
\setbox\scratchbox\vbox{\externalfigure[dummy]}
\fi

\newdimen\imgWidth
\newdimen\imgHeight
\imgWidth=\wd\scratchbox
\imgHeight=\ht\scratchbox
\newdimen\aspectPaper
\newdimen\aspectImg
\aspectPaper=\paperwidth
\aspectImg=\imgWidth
\divide\aspectPaper\paperheight
\divide\aspectImg\imgHeight
\stop

\ifdim\aspectImg>\aspectPaper
\defineexternalfigure [chapter] [width=\paperwidth]
\else
\defineexternalfigure [chapter] [height=\paperheight]
\fi

% include the right image corresponding to the chapter
\ifcase\ImageCounter
\or
\setlayer [chapterimages] {\externalfigure[cow][chapter]}
\or
\setlayer [chapterimages] {\externalfigure[mill][chapter]}
\else
\setlayer [chapterimages] {\externalfigure[dummy][chapter]}
\fi
\stopmakeup
\stopsetups


And here is short sample document for testing.

\starttext

\startchapter [title=First Chapter]
\startsection [title=Some section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\startchapter [title=Second Chapter]
\startsection [title=Some other section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\startchapter [title=Third Chapter]
\startsection [title=Some new section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\stoptext


## How it works

First I define a layer that contains the chapter images. Then I hook into the chapter command. The setup s:chapter is placed before every chapter. It ensures that the page is a left one. Next, the page headers and footers are suppressed.

Then follows some ugly code that ensures that the entire page is filled with the graphic and the borders are cut off. I would like to see a cleaner solution for this (Aditya and Phillipp, are you listening?).

Finally the images are included. You need to two create new entries for each chapter image. One for the aspect ratio calculation and one which is finally included. Don't forget to add the \or. When you include less images than chapters, the dummy graphic is used for the remaining chapters.

## Things to improve

The code to include the images is needed in two places, it would be much cleaner and less error-prone to define them only once.

As I mentioned before, the code to compute the full page images is not very ConTeXtish and can surely be improved. It doesn't center the graphic like in your sketch. The images are always left top aligned and cut off at the right or bottom.

EDIT: Here is a second version from phg (see comments below) with a more ConTeXtish interface and the advantage that the graphics are defined only once. It uses Lua to compare the graphic dimensions, since it tends to be quite tricky in TeX. Warning: More low-level, but rather pretty code ahead.

% macros=mkvi

% pretty dummy graphics
\useMPlibrary
[dum]

% fake text
\usemodule
[visual]

\setuppagenumbering
[alternative=doublesided]

\setupbackgrounds
[page]
[background=chapterimages]

\definelayer
[chapterimages]

[chapter]
[before=\setups{s:chapter}]

\definemakeup
[chapterimage]

% zero page borders for the makeup
\definelayout
[chapterimage]
[page]

\setupmakeup
[chapterimage]
[page=left]

\unprotect

\newcount\image_counter
\newdimen\image_ht
\newdimen\image_wd

\def\defineimagelist{\dodoubleempty\do_define_image_list}

\def\do_define_image_list[#structurename][#lst]{%
\edef\current_structure{#structurename}%
\scratchcounter\zerocount
\ifsecondargument
\processcommalist[#lst]\define_structure_image
\fi%
}

\def\define_structure_image#img{%
\expandafter\def
\csname\current_structure _image_\the\scratchcounter\endcsname{%
\externalfigure[#img]%
}%
}

\unexpanded\def\pickimage{\dosingleempty\do_pick_image}

\def\do_pick_image[#structurename]{%
\ifcsname#{structurename}_image_\the\image_counter\endcsname
\expandafter\let\expandafter%
\current_structure_image\csname#{structurename}_image_\the\image_counter\endcsname
\else
\let\current_structure_image\structure_image_dummy
\fi%
\setbox\scratchbox\vbox{\current_structure_image}%
\image_ht\ht\scratchbox
\image_wd\wd\scratchbox
\ctxcommand{test_image_dimensions()}
{\current_structure_image[width=\paperwidth]}
{\current_structure_image[height=\paperheight]}%
}

\def\structure_image_dummy{\externalfigure[dummy]}%

%% Since \externalfigure[foo][factor=max] doesn't work anymore, we'll
%% have to bypass TEX's inadequate integer arithmetic through Lua.
\startluacode
local td = tex.dimen
commands.test_image_dimensions = function ()
local pht, pwd = td.paperheight, td.paperwidth
local iht, iwd = td.image_ht,    td.image_wd
local result = iht / iwd > pht / pwd
commands.doifelse(result)
end
\stopluacode

\protect

\startsetups s:chapter
\startmakeup [chapterimage]
\pickimage [chapter]
\stopmakeup
\stopsetups


And here again the sample document, which is the same as in the example above, except that it contains a user interface to set up the graphics used for the chapter pages.

\starttext

\defineimagelist
[chapter]
[cow, mill, dummy]

\startchapter [title=First Chapter]
\startsection [title=Some section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\startchapter [title=Second Chapter]
\startsection [title=Some other section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\startchapter [title=Third Chapter]
\startsection [title=Some new section]
\fakewords{500}{1000}
\stopsection
\stopchapter

\stoptext


The result is the same as in the screen shots above. All credits for the code go to phg, all bugs are mine :)

Due to the mkvi syntax, the code should be self-explanatory. What it basically does, is creating a list of macros named after the section level (here “chapter”) and a number that increments with each image. These macros typeset the image with \externalfigure. The rest is similar to the first code.

-
You can pass the name of the figure file as an option to \startchapter: \startchapter[title={First chapter}][figure=cow] and then access the figure name in the setups using \structureuservariable{figure} –  Aditya Jun 6 '12 at 18:24
That way you scatter your markup with style information. I would prefer strict separation of both. –  Marco Jun 6 '12 at 18:27
I prefer specifying the figure as part of the section header information; automagic insertion of figures makes it hard to modify things later. But, it is a matter of personal preference. Another point. You can use \getfiguredimensions[figname] and then \figurenaturalwidth and \figurenaturalheight give you the figure dimensions. –  Aditya Jun 6 '12 at 18:38
No need to nil the header or footer as \startmakeup without parameters sets both to \v!empty. Also, instead of the explicit \page[left], you could \definemakeup[chapterimage][page] \setupmakeup[chapterimage][page=left] to make the code appear more orderly ;-). /Named/ makeups are a bit more complex, however as most of the time is spent on image processing anyways the speed loss I measured on a 600 page test document is neglegible (δ about 1s of 54s total). EDIT: btw. it’s Philipp. –  phg Jun 7 '12 at 7:33
Also it appears you can simplify your calculations. (1) remove \imgWidth and \imgHeight entirely. (2) move \newdimen \aspectPaper \newdimen \aspectImg outside the setups (can reuse the same dimension registers). (3) in order to calculate the aspects all you need now is \aspectPaper=\dimexpr(\paperwidth/\paperheight)\relax \aspectImg=\dimexpr(\wd\scratchbox/\ht\scratchbox)\relax. –  phg Jun 7 '12 at 7:49