+my $colors;
+my $valid_image_types;
+if (not RT->Config->Get('DisableGD') and Convert::Color->require) {
+ require GD;
+
+ # Always find out what GD can read...
+ my %gd_can;
+ for my $type (qw(Png Jpeg Gif)) {
+ $gd_can{$type}++ if GD::Image->can("newFrom${type}Data");
+ }
+ $valid_image_types = join(", ", map { uc } sort { lc $a cmp lc $b } keys %gd_can);
+}
+
+my $analyze_img = sub {
+ return undef unless $valid_image_types;
+
+ my $imgdata = shift;
+ return undef unless $imgdata;
+
+ # ...but only analyze the image if we have data
+ my $img = GD::Image->new($imgdata);
+ unless ($img) {
+ # This has to be one damn long line because the loc() needs to be
+ # source parsed correctly.
+ push @results, loc("Automatically suggested theme colors aren't available for your image. This might be because you uploaded an image type that your installed version of GD doesn't support. Supported types are: [_1]. You can recompile libgd and GD.pm to include support for other image types.", $valid_image_types);
+ return undef;
+ }
+
+ my %colors;
+
+ my @wsamples;
+ my @hsamples;
+ if ($img->width > 200) {
+ @wsamples = map { int($img->width*($_/200)) } (0..199);
+ } else {
+ @wsamples = ( 0 .. $img->width - 1 );
+ }
+ if ($img->height > 200) {
+ @hsamples = map { int($img->height*($_/200)) } (0..199);
+ } else {
+ @hsamples = ( 0 .. $img->height - 1 );
+ }
+ for my $i (@wsamples) {
+ for my $j (@hsamples) {
+ my @color = $img->rgb( $img->getPixel($i,$j) );
+ my $hsl = Convert::Color->new('rgb:'.join(',',map { $_ / 255 } @color))->convert_to('hsl');
+ my $c = join(',',@color);
+ next if $hsl->lightness < 0.1;
+ $colors{$c} ||= { h => $hsl->hue, s => $hsl->saturation, l => $hsl->lightness, cnt => 0, c => $c};
+ $colors{$c}->{cnt}++;
+ }
+ }
+
+ for (values %colors) {
+ $_->{rank} = $_->{s} * $_->{cnt};
+ }
+ my @top5 = grep { defined and $_->{'l'} and $_->{'c'} }
+ (sort { $b->{rank} <=> $a->{rank} } values %colors)[0..5];
+ return \@top5;
+};
+