4 Copyright(c)2008 Internet Archive. Software license AGPL version 3.
6 This file is part of BookReader.
8 The canonical short name of an image type is the same as in the MIME type.
9 For example both .jpeg and .jpg are considered to have type "jpeg" since
10 the MIME type is "image/jpeg".
12 BookReader is free software: you can redistribute it and/or modify
13 it under the terms of the GNU Affero General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
17 BookReader is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU Affero General Public License for more details.
22 You should have received a copy of the GNU Affero General Public License
23 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
26 $MIMES = array('gif' => 'image/gif',
28 'jpg' => 'image/jpeg',
29 'jpeg' => 'image/jpeg',
31 'tif' => 'image/tiff',
32 'tiff' => 'image/tiff');
34 $EXTENSIONS = array('gif' => 'gif',
42 $exiftool = '/petabox/sw/books/exiftool/exiftool';
44 // Process some of the request parameters
45 $zipPath = $_REQUEST['zip'];
46 $file = $_REQUEST['file'];
47 if (isset($_REQUEST['ext'])) {
48 $ext = $_REQUEST['ext'];
53 if (isset($_REQUEST['callback'])) {
55 $callback = $_REQUEST['callback'];
63 * Get info about requested image (input)
64 * Get info about requested output format
65 * Determine processing parameters
68 * Clean up temporary files
71 function getUnarchiveCommand($archivePath, $file)
73 $lowerPath = strtolower($archivePath);
74 if (preg_match('/\.([^\.]+)$/', $lowerPath, $matches)) {
75 $suffix = $matches[1];
77 if ($suffix == 'zip') {
79 . escapeshellarg($archivePath)
80 . ' ' . escapeshellarg($file);
81 } else if ($suffix == 'tar') {
83 . escapeshellarg($archivePath)
84 . ' ' . escapeshellarg($file);
86 BRfatal('Incompatible archive format');
90 BRfatal('Bad image stack path');
93 BRfatal('Bad image stack path or archive format');
98 * Returns the image type associated with the file extension.
100 function imageExtensionToType($extension)
104 if (array_key_exists($extension, $EXTENSIONS)) {
105 return $EXTENSIONS[$extension];
107 BRfatal('Unknown image extension');
112 * Get the image width, height and depth from a jp2 file in zip.
114 function getImageInfo($zipPath, $file)
118 $fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
119 $type = imageExtensionToType($fileExt);
121 // We look for all the possible tags of interest then act on the
122 // ones presumed present based on the file type
123 $tagsToGet = ' -ImageWidth -ImageHeight -FileType' // all formats
124 . ' -BitsPerComponent -ColorSpace' // jp2
125 . ' -BitDepth' // png
126 . ' -BitsPerSample'; // tiff
128 $cmd = getUnarchiveCommand($zipPath, $file)
129 . ' | '. $exiftool . ' -S -fast' . $tagsToGet . ' -';
133 foreach ($output as $line) {
134 $keyValue = explode(": ", $line);
135 $tags[$keyValue[0]] = $keyValue[1];
138 $width = intval($tags["ImageWidth"]);
139 $height = intval($tags["ImageHeight"]);
140 $type = strtolower($tags["FileType"]);
142 switch ($tags["FileType"]) {
144 $bits = intval($tags["BitsPerComponent"]);
147 $bits = intval($tags["BitsPerSample"]);
153 $bits = intval($tags["BitDepth"]);
156 BRfatal("Unsupported image type");
161 $retval = Array('width' => $width, 'height' => $height,
162 'bits' => $bits, 'type' => $type);
168 * Output JSON given the imageInfo associative array
170 function outputJSON($imageInfo, $callback)
172 header('Content-type: text/plain');
173 $jsonOutput = json_encode($imageInfo);
175 $jsonOutput = $callback . '(' . $jsonOutput . ');';
180 // Get the image size and depth
181 $imageInfo = getImageInfo($zipPath, $file);
183 // Output json if requested
184 if ('json' == $ext) {
185 outputJSON($imageInfo, $callback);
189 // Unfortunately kakadu requires us to know a priori if the
190 // output file should be .ppm or .pgm. By decompressing to
191 // .bmp kakadu will write a file we can consistently turn into
192 // .pnm. Really kakadu should support .pnm as the file output
193 // extension and automatically write ppm or pgm format as
195 $decompressToBmp = true;
196 if ($decompressToBmp) {
197 $stdoutLink = '/tmp/stdout.bmp';
199 $stdoutLink = '/tmp/stdout.ppm';
202 $fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
204 // Rotate is currently only supported for jp2 since it does not add server load
205 $allowedRotations = array("0", "90", "180", "270");
206 $rotate = $_REQUEST['rotate'];
207 if ( !in_array($rotate, $allowedRotations) ) {
211 // Image conversion options
213 $jpegOptions = '-quality 75';
215 // The pbmreduce reduction factor produces an image with dimension 1/n
216 // The kakadu reduction factor produceds an image with dimension 1/(2^n)
218 if (isset($_REQUEST['height'])) {
219 $ratio = floatval($_REQUEST['origHeight']) / floatval($_REQUEST['height']);
223 } else if ($ratio <= 4) {
227 //$powReduce = 3; //too blurry!
233 $scale = $_REQUEST['scale'];
237 } else if (2 == $scale) {
239 } else if (4 == $scale) {
241 } else if (8 == $scale) {
243 } else if (16 == $scale) {
245 } else if (32 == $scale) {
248 // $$$ Leaving this in as default though I'm not sure why it is...
254 if (!file_exists($stdoutLink))
256 system('ln -s /dev/stdout ' . $stdoutLink);
260 putenv('LD_LIBRARY_PATH=/petabox/sw/lib/kakadu');
262 $unzipCmd = getUnarchiveCommand($zipPath, $file);
264 if ('jp2' == $fileExt) {
266 " | /petabox/sw/bin/kdu_expand -no_seek -quiet -reduce $powReduce -rotate $rotate -i /dev/stdin -o " . $stdoutLink;
267 if ($decompressToBmp) {
268 $decompressCmd .= ' | bmptopnm ';
271 } else if ('tif' == $fileExt) {
272 // We need to create a temporary file for tifftopnm since it cannot
273 // work on a pipe (the file must be seekable).
274 // We use the BookReaderTiff prefix to give a hint in case things don't
276 $tempFile = tempnam("/tmp", "BookReaderTiff");
278 $pbmReduce = reduceCommand($scale);
281 ' > ' . $tempFile . ' ; tifftopnm ' . $tempFile . ' 2>/dev/null' . $pbmReduce;
283 } else if ('jpg' == $fileExt) {
284 $decompressCmd = ' | jpegtopnm ' . reduceCommand($scale);
286 } else if ('png' == $fileExt) {
287 $decompressCmd = ' | pngtopnm ' . reduceCommand($scale);
290 BRfatal('Unknown source file extension: ' . $fileExt);
293 // Non-integer scaling is currently disabled on the cluster
294 // if (isset($_REQUEST['height'])) {
295 // $cmd .= " | pnmscale -height {$_REQUEST['height']} ";
299 $compressCmd = ' | pnmtojpeg ' . $jpegOptions;
300 } else if ('png' == $ext) {
301 $compressCmd = ' | pnmtopng ' . $pngOptions;
304 if (($ext == $fileExt) && ($scale == 1) && ($rotate === "0")) {
305 // Just pass through original data if same format and size
308 $cmd = $unzipCmd . $decompressCmd . $compressCmd;
314 header('Content-type: ' . $MIMES[$ext]);
315 header('Cache-Control: max-age=15552000');
316 passthru ($cmd); # cmd returns image data
318 if (isset($tempFile)) {
322 function BRFatal($string) {
323 echo "alert('$string');\n";
327 // Returns true if using a power node
328 function onPowerNode() {
329 exec("lspci | fgrep -c Realtek", $output, $return);
330 if ("0" != $output[0]) {
333 exec("egrep -q AMD /proc/cpuinfo", $output, $return);
341 function reduceCommand($scale) {
344 return ' | pnmscale -reduce ' . $scale;
346 return ' | pnmscale -nomix -reduce ' . $scale;