source: main/trunk/greenstone2/perllib/plugins/ImageConverter.pm@ 24349

Last change on this file since 24349 was 24346, checked in by davidb, 13 years ago

With added support for orthogonal indexes (i.e. audioDB index in addition to a text-based one like mg) the Image Magick warning appears for each orthogonal index. This change limits it to print it out just once

  • Property svn:executable set to *
File size: 18.9 KB
Line 
1###########################################################################
2#
3# ImageConverter - helper plugin that does image conversion using ImageMagick
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 2008 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26package ImageConverter;
27
28use BaseMediaConverter;
29
30
31use strict;
32no strict 'refs'; # allow filehandles to be variables and viceversa
33
34use gsprintf 'gsprintf';
35
36BEGIN {
37 @ImageConverter::ISA = ('BaseMediaConverter');
38}
39
40# When used with multiple builder+buildproc, plugins loaded multiple times
41# => use this 'our' var to ensure only see the warning about ImageMagick once
42our $given_image_conversion_warning = 0;
43
44my $arguments = [
45 { 'name' => "create_thumbnail",
46 'desc' => "{ImageConverter.create_thumbnail}",
47 'type' => "enum",
48 'list' => [{'name' => "true", 'desc' => "{common.true}"},
49 {'name' => "false", 'desc' => "{common.false}"}],
50 'deft' => "true",
51 'reqd' => "no" },
52 { 'name' => "thumbnailsize",
53 'desc' => "{ImageConverter.thumbnailsize}",
54 'type' => "int",
55 'deft' => "100",
56 'range' => "1,",
57 'reqd' => "no" },
58 { 'name' => "thumbnailtype",
59 'desc' => "{ImageConverter.thumbnailtype}",
60 'type' => "string",
61 'deft' => "gif",
62 'reqd' => "no" },
63 { 'name' => "noscaleup",
64 'desc' => "{ImageConverter.noscaleup}",
65 'type' => "flag",
66 'reqd' => "no" },
67 { 'name' => "create_screenview",
68 'desc' => "{ImageConverter.create_screenview}",
69 'type' => "enum",
70 'list' => [{'name' => "true", 'desc' => "{common.true}"},
71 {'name' => "false", 'desc' => "{common.false}"}],
72 'deft' => "true",
73 'reqd' => "no" },
74 { 'name' => "screenviewsize",
75 'desc' => "{ImageConverter.screenviewsize}",
76 'type' => "int",
77 'deft' => "500",
78 'range' => "1,",
79 'reqd' => "no" },
80 { 'name' => "screenviewtype",
81 'desc' => "{ImageConverter.screenviewtype}",
82 'type' => "string",
83 'deft' => "jpg",
84 'reqd' => "no" },
85 { 'name' => "converttotype",
86 'desc' => "{ImageConverter.converttotype}",
87 'type' => "string",
88 'deft' => "",
89 'reqd' => "no" },
90 { 'name' => "minimumsize",
91 'desc' => "{ImageConverter.minimumsize}",
92 'type' => "int",
93 'deft' => "100",
94 'range' => "1,",
95 'reqd' => "no" }
96 ];
97
98my $options = { 'name' => "ImageConverter",
99 'desc' => "{ImageConverter.desc}",
100 'abstract' => "yes",
101 'inherits' => "yes",
102 'args' => $arguments };
103
104sub new {
105 my ($class) = shift (@_);
106 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
107 push(@$pluginlist, $class);
108
109 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
110 push(@{$hashArgOptLists->{"OptList"}},$options);
111
112 my $self = new BaseMediaConverter($pluginlist, $inputargs, $hashArgOptLists, 1);
113
114
115 return bless $self, $class;
116
117}
118
119# needs to be called after BasePlugin init, so that outhandle is set up.
120sub init {
121 my $self = shift(@_);
122
123 $self->{'tmp_file_paths'} = ();
124
125 # Check that ImageMagick is installed and available on the path
126 my $image_conversion_available = 1;
127 my $no_image_conversion_reason = "";
128 # None of this works very well on Windows 95/98...
129 if ($ENV{'GSDLOS'} eq "windows" && !Win32::IsWinNT()) {
130 $image_conversion_available = 0;
131 $no_image_conversion_reason = "win95notsupported";
132 } else {
133 my $result = `identify -help 2>&1`;
134 my $return_value = $?;
135
136 if ( ($ENV{'GSDLOS'} eq "windows" && $return_value == 256) || $return_value == -1) { # Linux and Windows return different values for "program not found"
137 $image_conversion_available = 0;
138 $no_image_conversion_reason = "imagemagicknotinstalled";
139 }
140 }
141 $self->{'image_conversion_available'} = $image_conversion_available;
142 $self->{'no_image_conversion_reason'} = $no_image_conversion_reason;
143
144 if ($self->{'image_conversion_available'} == 0) {
145 if (!$given_image_conversion_warning) {
146 my $outhandle = $self->{'outhandle'};
147 &gsprintf($outhandle, "ImageConverter: {ImageConverter.noconversionavailable} ({ImageConverter.".$self->{'no_image_conversion_reason'}."})\n");
148 $given_image_conversion_warning = 1;
149 }
150 }
151
152}
153
154
155# convert image to new type if converttotype is set
156# generate thumbnails if required
157# generate screenview if required
158# discover image metadata
159# filename_no_path must be in utf8 and url-encoded
160sub generate_images {
161 my $self = shift(@_);
162 my ($filename_full_path, $filename_encoded_full_path, $doc_obj, $section, $filename_encoding) = @_;
163
164 my ($unused_fefp,$filename_encoded_no_path)
165 = util::get_full_filenames("",$filename_encoded_full_path);
166
167 # The following is potentially very muddled thinking (but currently seems to work)
168 # generate_images currently called from ImagePlugin and PagedImagePlugin
169 my $filename_no_path = $filename_encoded_no_path;
170
171 # check image magick status
172 return 0 if $self->{'image_conversion_available'} == 0;
173
174 # check the filenames
175 return 0 if ($filename_no_path eq "" || !-f $filename_full_path);
176
177 if ($self->{'enable_cache'}) {
178 $self->init_cache_for_file($filename_full_path);
179 }
180 if ($self->{'store_file_paths'}) {
181 $self->{'orig_file'} = "";
182 $self->{'thumb_file'} = "";
183 $self->{'screen_file'} = "";
184 }
185 my $verbosity = $self->{'verbosity'};
186 my $outhandle = $self->{'outhandle'};
187
188 # check the size of the image against minimum size if specified
189 my $minimumsize = $self->{'minimumsize'};
190 if (defined $minimumsize && (-s $filename_full_path < $minimumsize)) {
191 print $outhandle "ImageConverter: \"$filename_full_path\" too small, skipping\n"
192 if ($verbosity > 1);
193 return 0; # or is there a better return value??
194 }
195
196 my $filehead = $filename_no_path;
197 $filehead =~ s/\.([^\.]*)$//; # filename with no extension
198 my $assocfilemeta = "[assocfilepath]";
199 if ($section ne $doc_obj->get_top_section()) {
200 $assocfilemeta = "[parent(Top):assocfilepath]";
201 }
202
203 # The images that will get generated may contain percent signs in their src filenames
204 # Encode those percent signs themselves so that urls to the imgs refer to them correctly
205 my $url_to_filehead = &unicode::filename_to_url($filehead);
206 my $url_to_filename_no_path = &unicode::filename_to_url($filename_no_path);
207
208 # Convert the image to a new type (if required).
209 my $converttotype = $self->{'converttotype'};
210 my $type = "unknown";
211
212 if ($converttotype ne "" && $filename_full_path !~ m/$converttotype$/) {
213# # $doc_obj->add_utf8_metadata($section, "Image", $utf8_filename_meta);
214
215 my ($result, $converted_filename_full_path)
216 = $self->convert($filename_full_path, $converttotype, "", "CONVERTTYPE");
217
218 $type = $converttotype;
219 $filename_full_path = $converted_filename_full_path;
220 $filename_no_path = "$filehead.$type";
221 $url_to_filename_no_path = "$url_to_filehead.$type";
222 if ($self->{'store_file_paths'}) {
223 $self->{'orig_file'} = $converted_filename_full_path;
224 }
225 }
226
227 # add Image metadata
228 $doc_obj->add_utf8_metadata($section, "Image", $url_to_filename_no_path); # url to generated image
229
230 # here we overwrite the original with the potentially converted one
231# $doc_obj->set_utf8_metadata_element($section, "Source", &unicode::url_decode($filename_no_path)); # displayname of generated image
232# $doc_obj->set_utf8_metadata_element($section, "SourceFile", $url_to_filename_no_path); # displayname of generated image
233
234# $self->set_Source_metadata($doc_obj,$url_to_filename_no_path,undef);
235
236 my $raw_filename_full_path = &unicode::url_decode($filename_encoded_full_path);
237 $self->set_Source_metadata($doc_obj,$raw_filename_full_path,
238 $filename_encoding, $section);
239
240
241 # use identify to get info about the (possibly converted) image
242 my ($image_type, $image_width, $image_height, $image_size)
243 = &identify($filename_full_path, $outhandle, $verbosity);
244
245 if ($image_type ne " ") {
246 $type = $self->correct_mime_type($image_type);
247 }
248
249 #overwrite the ones added in BasePlugin
250 $doc_obj->set_metadata_element ($section, "FileFormat", $type);
251 $doc_obj->set_metadata_element ($section, "FileSize", $image_size);
252
253 $doc_obj->add_metadata ($section, "ImageType", $image_type);
254 $doc_obj->add_metadata ($section, "ImageWidth", $image_width);
255 $doc_obj->add_metadata ($section, "ImageHeight", $image_height);
256 $doc_obj->add_metadata ($section, "ImageSize", $image_size);
257
258 if ((defined $self->{'MaxImageWidth'})
259 && ($image_width > $self->{'MaxImageWidth'})) {
260 $self->{'MaxImageWidth'} = $image_width;
261 }
262 if ((defined $self->{'MaxImageHeight'})
263 && ($image_height > $self->{'MaxImageHeight'})) {
264 $self->{'MaxImageHeight'} = $image_height;
265 }
266
267 # srclink_file is now deprecated because of the "_" in the metadataname. Use srclinkFile
268 $doc_obj->add_metadata ($section, "srclink_file", $url_to_filename_no_path);
269 $doc_obj->add_metadata ($section, "srclinkFile", $url_to_filename_no_path);
270 $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/$assocfilemeta/[srclinkFile]\" width=\"[ImageWidth]\" height=\"[ImageHeight]\">");
271
272 # Add the image as an associated file
273 $doc_obj->associate_file($filename_full_path, $filename_no_path, "image/$type", $section);
274
275 if ($self->{'create_thumbnail'} eq "true") {
276 $self->create_thumbnail($filename_full_path, $filehead, $doc_obj, $section, $assocfilemeta, $url_to_filehead);
277 }
278 if ($self->{'create_screenview'} eq "true") {
279 $self->create_screenview($filename_full_path, $filehead, $doc_obj, $section, $assocfilemeta, $url_to_filehead, $image_width, $image_height);
280 }
281
282 return 1;
283}
284
285sub create_thumbnail {
286 my $self = shift(@_);
287 my ($original_file, $filehead, $doc_obj, $section, $assocfilemeta, $url_to_filehead) = @_;
288 $url_to_filehead = $filehead unless defined $url_to_filehead;
289
290 my $thumbnailsize = $self->{'thumbnailsize'};
291 my $thumbnailtype = $self->correct_mime_type($self->{'thumbnailtype'});
292
293 # Generate the thumbnail with convert
294 my ($result,$thumbnailfile)
295 = $self->convert($original_file, $thumbnailtype, "-geometry $thumbnailsize" . "x$thumbnailsize", "THUMB");
296
297 # Add the thumbnail as an associated file ...
298 if (-e "$thumbnailfile") {
299 $doc_obj->associate_file("$thumbnailfile", $filehead."_thumb.$thumbnailtype",
300 "image/$thumbnailtype",$section); # name of generated image
301 $doc_obj->add_metadata ($section, "ThumbType", $thumbnailtype);
302 $doc_obj->add_utf8_metadata ($section, "Thumb", $url_to_filehead."_thumb.$thumbnailtype"); # url to generated image
303
304 $doc_obj->add_metadata ($section, "thumbicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/$assocfilemeta/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
305
306
307 # Extract Thumbnail metadata from convert output
308 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
309 $doc_obj->add_metadata ($section, "ThumbWidth", $1);
310 $doc_obj->add_metadata ($section, "ThumbHeight", $2);
311 }
312 if ($self->{'store_file_paths'}) {
313 $self->{'thumb_file'} = $thumbnailfile;
314 }
315
316 } else {
317 my $outhandle = $self->{'outhandle'};
318 print $outhandle "Couldn't find thumbnail $thumbnailfile\n";
319
320 }
321}
322
323sub create_screenview {
324
325 my $self = shift(@_);
326 my ($original_file, $filehead, $doc_obj, $section, $assocfilemeta, $url_to_filehead, $image_width, $image_height) = @_;
327 $url_to_filehead = $filehead unless defined $url_to_filehead;
328
329 my $screenviewsize = $self->{'screenviewsize'};
330 my $screenviewtype = $self->correct_mime_type($self->{'screenviewtype'});
331
332 # Scale the image, unless the original image is smaller than the screenview size and -noscaleup is set
333 my $scale_option = "-geometry $screenviewsize" . "x$screenviewsize";
334 if ($self->{'noscaleup'} && $image_width < $screenviewsize && $image_height < $screenviewsize)
335 {
336 $scale_option = "";
337 }
338
339 # make the screenview image
340 my ($result,$screenviewfilename)
341 = $self->convert($original_file, $screenviewtype, $scale_option, "SCREEN");
342
343 #add the screenview as an associated file ...
344 if (-e "$screenviewfilename") {
345 $doc_obj->associate_file("$screenviewfilename", $filehead."_screen.$screenviewtype", "image/$screenviewtype",$section); # name of generated image
346 $doc_obj->add_metadata ($section, "ScreenType", $screenviewtype);
347 $doc_obj->add_utf8_metadata ($section, "Screen", $url_to_filehead."_screen.$screenviewtype"); # url to generated image
348
349 $doc_obj->add_metadata ($section, "screenicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/$assocfilemeta/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
350
351 # get screenview dimensions, size and type
352 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
353 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
354 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
355 } elsif ($result =~ m/([0-9]+)x([0-9]+)/) {
356 #if the image hasn't changed size, the previous regex doesn't match
357 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
358 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
359 }
360
361 if ($self->{'store_file_paths'}) {
362 $self->{'screen_file'} = $screenviewfilename;
363 }
364
365 } else {
366 my $outhandle = $self->{'outhandle'};
367 print $outhandle "Couldn't find screenview file $screenviewfilename\n";
368
369 }
370
371}
372
373
374
375sub convert {
376 my $self = shift(@_);
377 my $source_file_path = shift(@_);
378 my $target_file_type = shift(@_);
379 my $convert_options = shift(@_) || "";
380 my $convert_id = shift(@_) || "";
381 my $cache_mode = shift(@_) || "";
382
383 my $outhandle = $self->{'outhandle'};
384 my $verbosity = $self->{'verbosity'};
385
386 my $source_file_no_path = &File::Basename::basename($source_file_path);
387
388 # Determine the full name and path of the output file
389 my $target_file_path;
390 if ($self->{'enable_cache'}) {
391 my $cached_image_dir = $self->{'cached_dir'};
392 my $image_root = $self->{'cached_file_root'};
393 $image_root .= "_$convert_id" if ($convert_id ne "");
394 my $image_file = "$image_root.$target_file_type";
395 $target_file_path = &util::filename_cat($cached_image_dir,$image_file);
396 }
397 else {
398 $target_file_path = &util::get_tmp_filename($target_file_type);
399 push(@{$self->{'tmp_file_paths'}}, $target_file_path);
400
401 # Output filename used to be parsed from result line:
402 # my ($ofilename) = ($result =~ m/=>(.*\.$target_file_type)/);
403 # by the function that called 'convert'
404 # but this is no longer needed, as output filename is now
405 # explicitly passed back
406 }
407
408 # Generate and run the convert command
409 my $convert_command = "convert -interlace plane -verbose $convert_options \"$source_file_path\" \"$target_file_path\"";
410
411 my $print_info = { 'message_prefix' => $convert_id,
412 'message' => "Converting image $source_file_no_path to: $convert_id $target_file_type" };
413 $print_info->{'cache_mode'} = $cache_mode if ($cache_mode ne "");
414
415 my ($regenerated,$result,$had_error)
416 = $self->autorun_general_cmd($convert_command,$source_file_path,$target_file_path,$print_info);
417
418 return ($result,$target_file_path);
419}
420
421sub convert_without_result {
422 my $self = shift(@_);
423
424 my $source_file_path = shift(@_);
425 my $target_file_type = shift(@_);
426 my $convert_options = shift(@_) || "";
427 my $convert_id = shift(@_) || "";
428
429 return $self->convert($source_file_path,$target_file_type,
430 $convert_options,$convert_id,"without_result");
431}
432
433
434# Discover the characteristics of an image file with the ImageMagick
435# "identify" command.
436
437sub identify {
438 my ($image, $outhandle, $verbosity) = @_;
439
440 # Use the ImageMagick "identify" command to get the file specs
441 my $command = "identify \"$image\" 2>&1";
442 print $outhandle "$command\n" if ($verbosity > 2);
443 my $result = '';
444 $result = `$command`;
445 print $outhandle "$result\n" if ($verbosity > 3);
446
447 # Read the type, width, and height
448 my $type = 'unknown';
449 my $width = 'unknown';
450 my $height = 'unknown';
451
452 my $image_safe = quotemeta $image;
453 if ($result =~ /^$image_safe (\w+) (\d+)x(\d+)/) {
454 $type = $1;
455 $width = $2;
456 $height = $3;
457 }
458
459 # Read the size
460 my $size = "unknown";
461 if ($result =~ m/^.* ([0-9]+)b/) {
462 $size = $1;
463 }
464 elsif ($result =~ m/^.* ([0-9]+)(\.([0-9]+))?kb?/) {
465 $size = 1024 * $1;
466 if (defined($2)) {
467 $size = $size + (1024 * $2);
468 # Truncate size (it isn't going to be very accurate anyway)
469 $size = int($size);
470 }
471 }
472 elsif ($result =~ m/^.* ([0-9]+)(\.([0-9]+))?mb?/) {
473 $size = 1024 * 1024 * $1;
474 if (defined($2)) {
475 $size = $size + (1024 * 1024 * $2);
476 # Truncate size (it isn't going to be very accurate anyway)
477 $size = int($size);
478 }
479 }
480 elsif ($result =~ m/^.* (([0-9]+)(\.([0-9]+))?e\+([0-9]+))(kb|b)?/) {
481 # Deals with file sizes on Linux of type "3.4e+02kb" where e+02 is 1*10^2.
482 # 3.4e+02 therefore evaluates to 3.4 x 1 x 10^2 = 340kb.
483 # Programming languages including Perl know how that 3.4e+02 is a number,
484 # so we don't need to do any calculations.
485 $size = $1*1; # turn the string into a number by multiplying it by 1
486 #if we did $size = $1; $size would be merely the string "3.4e+02"
487 $size = int($size); # truncate size
488 }
489 print $outhandle "file: $image:\t $type, $width, $height, $size\n"
490 if ($verbosity > 2);
491
492 # Return the specs
493 return ($type, $width, $height, $size);
494}
495
496sub clean_up_temporary_files {
497 my $self = shift(@_);
498
499 foreach my $tmp_file_path (@{$self->{'tmp_file_paths'}}) {
500 if (-e $tmp_file_path) {
501 &util::rm($tmp_file_path);
502 }
503 }
504
505}
506
507# image/jpg is not a valid mime-type, it ought to be image/jpeg.
508# Sometimes JPEG is passed in also, want to keep things lowercase just in case.
509sub correct_mime_type {
510 my $self = shift(@_);
511 my ($file_extension) = @_;
512
513 $file_extension = lc($file_extension);
514 $file_extension =~ s/jpg/jpeg/s;
515
516 return $file_extension;
517}
518
5191;
Note: See TracBrowser for help on using the repository browser.