summaryrefslogtreecommitdiff
path: root/magick/profile.c
blob: 27596fcbc411a318b0ded79e52ec48cf3ed76827 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
/*
% Copyright (C) 2003-2017 GraphicsMagick Group
% Copyright (C) 2002 ImageMagick Studio
% Copyright 1991-1999 E. I. du Pont de Nemours and Company
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%              PPPP   RRRR    OOO   FFFFF  IIIII  L      EEEEE                %
%              P   P  R   R  O   O  F        I    L      E                    %
%              PPPP   RRRR   O   O  FFF      I    L      EEE                  %
%              P      R R    O   O  F        I    L      E                    %
%              P      R  R    OOO   F      IIIII  LLLLL  EEEEE                %
%                                                                             %
%                   GraphicsMagick Image Profile Methods                      %
%                                                                             %
%                                                                             %
%                              Software Design                                %
%                                John Cristy                                  %
%                               Bill Radcliffe                                %
%                              Bob Friesenhahn                                %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/

/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/analyze.h"
#include "magick/color.h"
#include "magick/composite.h"
#include "magick/log.h"
#include "magick/map.h"
#include "magick/monitor.h"
#include "magick/omp_data_view.h"
#include "magick/pixel_iterator.h"
#include "magick/profile.h"
#include "magick/quantize.h"
#include "magick/resize.h"
#include "magick/transform.h"
#include "magick/utility.h"
#if defined(HasLCMS)
#  if defined(HAVE_LCMS2_LCMS2_H)
#    include <lcms2/lcms2.h>
#  elif defined(HAVE_LCMS2_H)
#    include <lcms2.h>
#  else
#    error "LCMS 2 header missing!"
#  endif
#endif

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     A l l o c a t e I m a g e P r o f i l e I t e r a t o r                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  AllocateImageProfileIterator allocates an iterator to traverse the
%  image profile list.  It is an error (i.e. will surely crash) to invoke
%  DeleteImageProfile() on the profile that the iterator is currently
%  referencing.  However, it is safe to delete a profile that the iterator
%  is not currently referencing. Inserting additional profiles does not
%  invalidate the current iterator.
%
%
%  The format of the AllocateImageProfileIterator method is:
%
%      ImageProfileIterator AllocateImageProfileIterator(const Image *image)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
*/
MagickExport ImageProfileIterator
AllocateImageProfileIterator(const Image *image)
{
  if (!image->profiles)
    return 0;

  return (ImageProfileIterator) MagickMapAllocateIterator(image->profiles);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     A p p e n d I m a g e P r o f i l e                                     %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  AppendImageProfile adds a named profile to the image. If a profile with the
%  same name already exists, then the new profile data is appended to the
%  existing profile. If a null profile address is supplied, then an existing
%  profile is removed. The profile is copied into the image. Note that this
%  function does not execute CMS color profiles. Any existing CMS color
%  profile is simply added/updated. Use the ProfileImage() function in order
%  to execute a CMS color profile.
%
%  The format of the AppendImageProfile method is:
%
%      MaickPassFail AppendImageProfile(Image *image,const char *name,
%                                       const unsigned char *profile_chunk,
%                                       const size_t chunk_length)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
%    o name: Profile name. Valid names are "8BIM", "ICM", "IPTC", XMP, or any
%                          unique text string.
%
%    o profile_chunk: Address of profile chunk to add or append. Pass zero
%               to remove an existing profile.
%
%    o length: The length of the profile chunk to add or append.
%
*/
MagickExport MagickPassFail
AppendImageProfile(Image *image,
                   const char *name,
                   const unsigned char *profile_chunk,
                   const size_t chunk_length)
{
  const unsigned char
    *existing_profile;

  size_t
    existing_length;

  MagickPassFail
    status;

  status=MagickFail;
  existing_length=0;
  existing_profile=(const unsigned char *) NULL;
  if (profile_chunk != (const unsigned char *) NULL)
    existing_profile=GetImageProfile(image,name,&existing_length);

  if ((profile_chunk == (const unsigned char *) NULL) ||
      (existing_profile == (const unsigned char *) NULL))
    {
      status=SetImageProfile(image,name,profile_chunk,chunk_length);
    }
  else
    {
      unsigned char
        *profile;

      size_t
        profile_length;

      profile_length=existing_length+chunk_length;
      if ((profile_length < existing_length) ||
          ((profile=MagickAllocateMemory(unsigned char *,(size_t) profile_length)) ==
           (unsigned char *) NULL))
        ThrowBinaryException(ResourceLimitError,MemoryAllocationFailed,
                             (char *) NULL);
      (void) memcpy(profile,existing_profile,existing_length);
      (void) memcpy(profile+existing_length,profile_chunk,chunk_length);
      status=SetImageProfile(image,name,profile,profile_length);
      MagickFreeMemory(profile);
    }

  return status;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     D e a l l o c a t e I m a g e P r o f i l e I t e r a t o r             %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  DeallocateImageProfileIterator deallocates an image profile iterator.
%
%  The format of the DeallocateImageProfileIterator method is:
%
%      void DeallocateImageProfileIterator(ImageProfileIterator profile_iterator)
%
%  A description of each parameter follows:
%
%    o profile_iterator: Profile iterator to deallocate.
%
*/
MagickExport void
DeallocateImageProfileIterator(ImageProfileIterator profile_iterator)
{
  if (profile_iterator != 0)
    MagickMapDeallocateIterator((MagickMapIterator) profile_iterator);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     D e l e t e I m a g e P r o f i l e                                     %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  DeleteImageProfile removes a named profile from the image.
%
%  The format of the DeleteImageProfile method is:
%
%      unsigned int DeleteImageProfile(Image *image,const char *name)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
%    o name: Profile name. Valid names are "8BIM", "ICM", & "IPTC" or a
%                          generic profile name.
%
*/
MagickExport MagickPassFail
DeleteImageProfile(Image *image,const char *name)
{
  return(SetImageProfile(image,name,0,0));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     G e t I m a g e P r o f i l e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetImageProfile returns a pointer to the named image profile if it is
%  present. A null pointer is returned if the named profile is not present.
%
%  Older versions of this function stored profiles named "8BIM" and "IPTC"
%  in the same storage location.  This is no longer the case.  However,
%  GetImageProfile() will try the alternate name if the specifically
%  requested profile name is not available.
%
%  The format of the GetImageProfile method is:
%
%      const unsigned char *GetImageProfile(const Image* image,
%                             const char *name, size_t *length)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
%    o name: Profile name. Valid names are "8BIM", "ICM", "IPTC", "XMP" or any
%                          unique text string.
%
%    o length: Updated with profile length if profile is present.  Set to NULL
%              if length is not needed.
%
*/
MagickExport const unsigned char *
GetImageProfile(const Image* image, const char *name, size_t *length)
{
  const unsigned char
    *profile = 0;

  size_t
    profile_length=0;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  assert(name != NULL);

  if (length)
    *length=0;

  if (!image->profiles)
    return 0;

  profile=MagickMapAccessEntry(image->profiles,name,&profile_length);

  if (!profile)
    {
      /*
        Support common alias names and work-alikes.
      */
      if (LocaleCompare("ICC",name) == 0)
        profile=MagickMapAccessEntry(image->profiles,"ICM",&profile_length);
      else if (LocaleCompare("ICM",name) == 0)
        profile=MagickMapAccessEntry(image->profiles,"ICC",&profile_length);
      else if (LocaleCompare("IPTC",name) == 0)
        profile=MagickMapAccessEntry(image->profiles,"8BIM",&profile_length);
      else if (LocaleCompare("8BIM",name) == 0)
        profile=MagickMapAccessEntry(image->profiles,"IPTC",&profile_length);
    }

  if (length)
    *length=profile_length;

  return profile;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     N e x t I m a g e P r o f i l e                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  NextImageProfile iterates forward to the next image profile. The profile
%  name is returned along with the profile data, and length.  If there are
%  no more entries in the list, then MagickFail is returned.
%
%  The format of the AllocateImageProfileIterator method is:
%
%      MagickPassFail NextImageProfile(ImageProfileIterator profile_iterator,
%                             const char **name, const unsigned char **profile,
%                             size_t *length)
%
%  A description of each parameter follows:
%
%    o profile_iterator: Profile iterator.
%
%    o name: Address of pointer to update with address of name.
%
%    o profile: Address of pointer to update with location of profile data.
%
%    o length: Address of parameter to update with profile length.
%
*/
MagickExport MagickPassFail
NextImageProfile(ImageProfileIterator profile_iterator,
                 const char **name,
                 const unsigned char **profile,
                 size_t *length)
{
  MagickMapIterator
    map_iterator;

  MagickPassFail
    status;

  assert(name != (const char **) NULL);
  assert(length != (size_t *) NULL);

  if (profile_iterator == 0)
    return (MagickFail);

  map_iterator=(MagickMapIterator) profile_iterator;
  status=MagickMapIterateNext(map_iterator,name);
  if (status != MagickFail)
    *profile=MagickMapDereferenceIterator(map_iterator,length);
  return (status);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   P r o f i l e I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ProfileImage() adds, applies, or removes a ICM, IPTC, or generic profile
%  from an image.  If the profile is NULL, it is removed from the image
%  otherwise added (or applied).  Use a name of '*' and a profile of NULL to
%  remove all profiles from the image. Ownership of the profile is
%  transferred to GraphicsMagick (it should not be altered or deallocated)
%  unless the clone option is set to True.
%
%  ICC ICM profiles are a special case and are handled as follows:
%
%  If there is no ICM profile currently associated with the image, then
%  the profile is simply associated with the image and the image pixels
%  are not altered.
%
%  If there is already a ICM profile associated with the image, then
%  the colorspace transform described by the existing and new profiles
%  is applied to the image pixels, and the new profile is associated
%  with the image.
%
%  The format of the ProfileImage method is:
%
%      unsigned int ProfileImage(Image *image,const char *name,
%        unsigned char *profile,const size_t length,unsigned int clone)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
%    o name: Name of profile to add or remove: ICM, IPTC, or generic profile.
%
%    o profile: The profile.  Can not be 'const' due to 'clone' option but
%             is treated as 'const' if 'clone' is set to MagickTrue.
%
%    o length: The length of the profile.
%
%    o clone: If set True, then copy the profile rather than taking
%             ownership of it.
%
%
*/
#if defined(HasLCMS)

typedef struct _ProfilePacket
{
  unsigned short
    red,
    green,
    blue,
    black;
} ProfilePacket;

typedef struct _TransformInfo
{
  Image           *image;             /* image handle */
  cmsHPROFILE     source_profile;     /* input profile */
  cmsHPROFILE     target_profile;     /* output profile */
  cmsUInt32Number source_type;        /* input pixel format */
  cmsUInt32Number target_type;        /* output pixel format */
  int             intent;             /* rendering intent */
  cmsUInt32Number flags;              /* create transform flags */
  ThreadViewDataSet *transform;       /* Thread-specific transforms */
  ColorspaceType  source_colorspace;  /* source image transform colorspace */
  ColorspaceType  target_colorspace;  /* target image transform colorspace */
  unsigned long   signature;          /* structure validation signature */
} TransformInfo;

static void
lcmsReplacementErrorHandler(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText)
{
  TransformInfo
    *xform;

  ExceptionType
    type=TransformError;

  xform=(TransformInfo *) ContextID;

  switch(ErrorCode)
  {
  default:
    type=TransformWarning;
    break;
  }

  (void) LogMagickEvent(type,GetMagickModule(),"lcms: #%u, %s",
                        ErrorCode,(ErrorText != (char *) NULL) ? ErrorText : "No error text");

  if (xform != (TransformInfo *) NULL)
    {
      ThrowException2(&xform->image->exception,type,"UnableToTransformColorspace",
                     (ErrorText != (char *) NULL) ? ErrorText : "No error text");
    }
}

static MagickPassFail
ProfileImagePixels(void *mutable_data,         /* User provided mutable data */
                   const void *immutable_data, /* User provided immutable data */
                   Image * restrict image,               /* Modify image */
                   PixelPacket * restrict pixels,        /* Pixel row */
                   IndexPacket * restrict indexes,       /* Pixel row indexes */
                   const long npixels,         /* Number of pixels in row */
                   ExceptionInfo *exception)   /* Exception report */
{
  const TransformInfo
    *xform = (const TransformInfo *) immutable_data;

  register long
    i;

  cmsHTRANSFORM
    transform;

  const ColorspaceType
    source_colorspace = xform->source_colorspace;

  const ColorspaceType
    target_colorspace = xform->target_colorspace;

  ProfilePacket
    alpha,
    beta;

  ARG_NOT_USED(mutable_data);
  ARG_NOT_USED(exception);

  transform=(cmsHTRANSFORM) AccessThreadViewData(xform->transform);

  /*
    TODO: This may be optimized to use PixelPackets instead
    of moving PixelPacket components to and from ProfilePackets.
    The transform types below, then, must match #ifdef's in the
    PixelPacket struct definition and should be optimized
    based on Quantum size. Some (if not all?) YCbCr and LUV
    profiles are (TIFF) scanline oriented, so transforming
    one pixel at a time does not work for those profiles.

    Notice that the performance penalty of transforming only
    one pixel at a time is very small and probably not worth
    optimizing.
  */

  for (i=0; i < npixels; i++)
    {
      alpha.red=ScaleQuantumToShort(pixels[i].red);
      if (source_colorspace != GRAYColorspace)
        {
          alpha.green=ScaleQuantumToShort(pixels[i].green);
          alpha.blue=ScaleQuantumToShort(pixels[i].blue);
          if (source_colorspace == CMYKColorspace)
            alpha.black=ScaleQuantumToShort(pixels[i].opacity);
        }
      cmsDoTransform(transform,&alpha,&beta,1);
      pixels[i].red=ScaleShortToQuantum(beta.red);
      if (IsGrayColorspace(target_colorspace))
        {
          pixels[i].green=pixels[i].red;
          pixels[i].blue=pixels[i].red;
        }
      else
        {
          pixels[i].green=ScaleShortToQuantum(beta.green);
          pixels[i].blue=ScaleShortToQuantum(beta.blue);
        }
      if (image->matte)
        {
          if ((source_colorspace == CMYKColorspace) &&
              (target_colorspace != CMYKColorspace))
            pixels[i].opacity=indexes[i];
          else
            if ((source_colorspace != CMYKColorspace) &&
                (target_colorspace == CMYKColorspace))
              indexes[i]=pixels[i].opacity;
        }
      if (target_colorspace == CMYKColorspace)
        pixels[i].opacity=ScaleShortToQuantum(beta.black);
    }

  return MagickPass;
}

static void MagickFreeCMSTransform(void * cmsTransformVoid)
{
  cmsHTRANSFORM
    cmsTransform=(cmsHTRANSFORM) cmsTransformVoid;

  if (cmsTransform != (cmsHTRANSFORM) NULL)
      cmsDeleteTransform(cmsTransform);
}

static const char *
PixelTypeToString(int pixel_type)
{
const char *
  result="";

  switch (pixel_type)
    {
    case PT_ANY:    result="ANY"   ; break;
    case PT_GRAY:   result="GRAY"  ; break;
    case PT_RGB:    result="RGB"   ; break;
    case PT_CMY:    result="CMY"   ; break;
    case PT_CMYK:   result="CMYK"  ; break;
    case PT_YCbCr:  result="YCbCr" ; break;
    case PT_YUV:    result="YUV (Lu'v')"; break;
    case PT_XYZ:    result="XYZ"   ; break;
    case PT_Lab:    result="Lab"   ; break;
    case PT_YUVK:   result="YUVK (Lu'v'K)" ; break;
    case PT_HSV:    result="HSV"   ; break;
    case PT_HLS:    result="HLS"   ; break;
    case PT_Yxy:    result="Yxy"   ; break;

#if defined(PT_HiFi)
    case PT_HiFi:   result="HiFi"  ; break;
#endif
#if defined(PT_HiFi7)
    case PT_HiFi7:  result="HiFi7" ; break;
#endif
#if defined(PT_HiFi8)
    case PT_HiFi8:  result="HiFi8" ; break;
#endif
#if defined(PT_HiFi9)
    case PT_HiFi9:  result="HiFi9" ; break;
#endif
#if defined(PT_HiFi10)
    case PT_HiFi10: result="HiFi10"; break;
#endif
#if defined(PT_HiFi11)
    case PT_HiFi11: result="HiFi11"; break;
#endif
#if defined(PT_HiFi12)
    case PT_HiFi12: result="HiFi12"; break;
#endif
#if defined(PT_HiFi13)
    case PT_HiFi13: result="HiFi13"; break;
#endif
#if defined(PT_HiFi14)
    case PT_HiFi14: result="HiFi14"; break;
#endif
#if defined(PT_HiFi15)
    case PT_HiFi15: result="HiFi15"; break;
#endif

#if defined(PT_MCH1)
    case PT_MCH1:   result="MCH1"  ; break;
#endif
#if defined(PT_MCH2)
    case PT_MCH2:   result="MCH2"  ; break;
#endif
#if defined(PT_MCH3)
    case PT_MCH3:   result="MCH3"  ; break;
#endif
#if defined(PT_MCH4)
    case PT_MCH4:   result="MCH4"  ; break;
#endif
#if defined(PT_MCH5)
    case PT_MCH5:   result="MCH5"  ; break;
#endif
#if defined(PT_MCH6)
    case PT_MCH6:   result="MCH6"  ; break;
#endif
#if defined(PT_MCH7)
    case PT_MCH7:   result="MCH7"  ; break;
#endif
#if defined(PT_MCH8)
    case PT_MCH8:   result="MCH8"  ; break;
#endif
#if defined(PT_MCH9)
    case PT_MCH9:   result="MCH9"  ; break;
#endif
#if defined(PT_MCH10)
    case PT_MCH10:  result="MCH10" ; break;
#endif
#if defined(PT_MCH11)
    case PT_MCH11:  result="MCH11" ; break;
#endif
#if defined(PT_MCH12)
    case PT_MCH12:  result="MCH12" ; break;
#endif
#if defined(PT_MCH13)
    case PT_MCH13:  result="MCH13" ; break;
#endif
#if defined(PT_MCH14)
    case PT_MCH14:  result="MCH14" ; break;
#endif
#if defined(PT_MCH15)
    case PT_MCH15:  result="MCH15" ; break;
#endif
#if defined(PT_LabV2)
    case PT_LabV2:  result="LabV2" ; break;
#endif
    }

  return result;
}

#endif /* defined(HasLCMS) */

#define ProfileImageText "[%s] Color Transform Pixels..."
MagickExport MagickPassFail
ProfileImage(Image *image,const char *name,unsigned char *profile,
             const size_t length,MagickBool clone)
{
  MagickPassFail
    status=MagickPass;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (name == (const char *) NULL)
    ThrowBinaryException3(OptionError,NoProfileNameWasGiven,
                          UnableToAddOrRemoveProfile);
  if ((profile == (const unsigned char *) NULL) || (length == 0))
    {
      /*
        Remove an ICM, IPTC, or generic profile from the image.
      */
      char
        arg_string[MaxTextExtent],
        profile_remove[MaxTextExtent];

      const char
        *profile_name;

      size_t
        profile_length;

      const unsigned char *
        profile_info;

      ImageProfileIterator
        profile_iterator;

      char
        **argv;

      int
        argc;

      long
        i;

      (void) strlcpy(arg_string,name,sizeof(arg_string));
      LocaleUpper(arg_string);
      for (i=0; arg_string[i] != '\0'; i++)
        if (arg_string[i] == ',')
          arg_string[i] = ' ';
      argv=StringToArgv(arg_string,&argc);
      profile_iterator=AllocateImageProfileIterator(image);
      profile_remove[0]=0;
      while(NextImageProfile(profile_iterator,&profile_name,&profile_info,
                             &profile_length) != MagickFail)
        {
          if (strlen(profile_remove))
            {
              (void) DeleteImageProfile(image,profile_remove);
              profile_remove[0]=0;
            }
          for (i=1 ; i < argc ; i++)
            {
              if ((*argv[i] == '!') && (LocaleCompare(profile_name,argv[i]+1) == 0))
                break;
              if (GlobExpression(profile_name,argv[i]))
                {
                  (void) strlcpy(profile_remove,profile_name,sizeof(profile_remove));
                  break;
                }
            }
        }
      DeallocateImageProfileIterator(profile_iterator);
      if (strlen(profile_remove))
        (void) DeleteImageProfile(image,profile_remove);

      for(i=0; argv[i] != NULL; i++)
        MagickFreeMemory(argv[i]);
      MagickFreeMemory(argv);

      return(MagickPass);
    }
  /*
    Add a ICM, IPTC, or generic profile to the image.
  */
  if ((LocaleCompare("8bim",name) == 0) || (LocaleCompare("iptc",name) == 0))
    {
      if (clone)
        {
          (void) SetImageProfile(image,name,profile,length);
        }
      else
        {
          (void) SetImageProfile(image,name,profile,length);
          MagickFreeMemory(profile);
        }
      return(MagickPass);
    }
  if (LocaleCompare("icm",name) == 0)
    {
      const unsigned char
        *existing_profile;

      size_t
        existing_profile_length=0;

      /* Check for identical input and output profiles. Return on identity. */
      existing_profile=GetImageProfile(image,"ICM",&existing_profile_length);

      (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                            "New Profile: %lu bytes, Existing Profile: %lu bytes",
                            (unsigned long) length,
                            (unsigned long) existing_profile_length);

      if ((length != 0) && (length == existing_profile_length) &&
          (memcmp(existing_profile,profile,length) == 0))
        {
          return(MagickPass);
        }

      /* Convert to new colors if we have both an old and a new profile. */
      if ((existing_profile_length != 0) && (length != 0))
        {
#if defined(HasLCMS)

          TransformInfo
            xform;

          MagickBool
            transform_colormap;

          /*
            Transform pixel colors as defined by the color profiles.
          */
          (void) memset(&xform,0,sizeof(xform));
          xform.signature=MagickSignature;
          xform.image=image;
          cmsSetLogErrorHandler(lcmsReplacementErrorHandler);

          xform.source_profile=cmsOpenProfileFromMemTHR((cmsContext) &xform,
                                                        (unsigned char *) existing_profile,
                                                        (cmsUInt32Number) existing_profile_length);
          xform.target_profile=cmsOpenProfileFromMemTHR((cmsContext) &xform,
                                                        (unsigned char *) profile,
                                                        (cmsUInt32Number) length);
          if ((xform.source_profile == (cmsHPROFILE) NULL) ||
              (xform.target_profile == (cmsHPROFILE) NULL))
            ThrowBinaryException3(ResourceLimitError,UnableToManageColor,
                                  UnableToOpenColorProfile);

          switch (cmsGetColorSpace(xform.source_profile))
            {
            case cmsSigXYZData:
              {
                xform.source_colorspace=XYZColorspace;
                xform.source_type=TYPE_XYZ_16;
                break;
              }
            case cmsSigLabData:
              {
                xform.source_colorspace=LABColorspace;
                xform.source_type=TYPE_Lab_16;
                break;
              }
            case cmsSigCmykData:
              {
                xform.source_colorspace=CMYKColorspace;
                xform.source_type=TYPE_CMYK_16;
                break;
              }
            case cmsSigYCbCrData:
              {
                xform.source_colorspace=YCbCrColorspace;
                xform.source_type=TYPE_YCbCr_16;
                break;
              }
            case cmsSigLuvData:
              {
                xform.source_colorspace=YUVColorspace;
                xform.source_type=TYPE_YUV_16;
                break;
              }
            case cmsSigGrayData:
              {
                xform.source_colorspace=GRAYColorspace;
                xform.source_type=TYPE_GRAY_16;
                break;
              }
            case cmsSigRgbData:
              {
                xform.source_colorspace=RGBColorspace;
                xform.source_type=TYPE_RGB_16;
                break;
              }
            default:
              {
                xform.source_colorspace=UndefinedColorspace;
                xform.source_type=TYPE_RGB_16;
                break;
              }
            }
          switch (cmsGetColorSpace(xform.target_profile))
            {
            case cmsSigXYZData:
              {
                xform.target_colorspace=XYZColorspace;
                xform.target_type=TYPE_XYZ_16;
                break;
              }
            case cmsSigLabData:
              {
                xform.target_colorspace=LABColorspace;
                xform.target_type=TYPE_Lab_16;;
                break;
              }
            case cmsSigCmykData:
              {
                xform.target_colorspace=CMYKColorspace;
                xform.target_type=TYPE_CMYK_16;
                break;
              }
            case cmsSigYCbCrData:
              {
                xform.target_colorspace=YCbCrColorspace;
                xform.target_type=TYPE_YCbCr_16;
                break;
              }
            case cmsSigLuvData:
              {
                xform.target_colorspace=YUVColorspace;
                xform.target_type=TYPE_YUV_16;
                break;
              }
            case cmsSigGrayData:
              {
                xform.target_colorspace=GRAYColorspace;
                xform.target_type=TYPE_GRAY_16;
                break;
              }
            case cmsSigRgbData:
              {
                xform.target_colorspace=RGBColorspace;
                xform.target_type=TYPE_RGB_16;
                break;
              }
            default:
              {
                xform.target_colorspace=UndefinedColorspace;
                xform.target_type=TYPE_RGB_16;
                break;
              }
            }

          /* Colorspace undefined */
          if ((xform.source_colorspace == UndefinedColorspace) ||
              (xform.target_colorspace == UndefinedColorspace))
            {
              (void) cmsCloseProfile(xform.source_profile);
              (void) cmsCloseProfile(xform.target_profile);
              ThrowBinaryException3(ImageError,UnableToAssignProfile,
                                    ColorspaceColorProfileMismatch);
            }
          /* Gray colorspace */
          if (IsGrayColorspace(xform.source_colorspace) &&
              !IsGrayImage(image,&image->exception))
            {
              (void) cmsCloseProfile(xform.source_profile);
              (void) cmsCloseProfile(xform.target_profile);
              ThrowBinaryException3(ImageError,UnableToAssignProfile,
                                    ColorspaceColorProfileMismatch);
            }
          /* CMYK colorspace */
          if (IsCMYKColorspace(xform.source_colorspace) &&
              !IsCMYKColorspace(image->colorspace))
            {
              (void) cmsCloseProfile(xform.source_profile);
              (void) cmsCloseProfile(xform.target_profile);
              ThrowBinaryException3(ImageError,UnableToAssignProfile,
                                    ColorspaceColorProfileMismatch);
            }
          /* YCbCr colorspace */
          if (IsYCbCrColorspace(xform.source_colorspace) &&
              !IsYCbCrColorspace(image->colorspace))
            {
              (void) cmsCloseProfile(xform.source_profile);
              (void) cmsCloseProfile(xform.target_profile);
              ThrowBinaryException3(ImageError,UnableToAssignProfile,
                                    ColorspaceColorProfileMismatch);
            }
          /* Verify that source colorspace type is supported */
          if (!IsGrayColorspace(xform.source_colorspace) &&
              !IsCMYKColorspace(xform.source_colorspace) &&
              !IsLABColorspace(xform.source_colorspace) &&
              !IsYCbCrColorspace(xform.source_colorspace) &&
              !IsRGBColorspace(image->colorspace))
            {
              (void) cmsCloseProfile(xform.source_profile);
              (void) cmsCloseProfile(xform.target_profile);
              ThrowBinaryException3(ImageError,UnableToAssignProfile,
                                    ColorspaceColorProfileMismatch);
            }

          (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                "Source pixel format: COLORSPACE=%s SWAPFIRST=%d "
                                "FLAVOR=%d PLANAR=%d ENDIAN16=%d DOSWAP=%d "
                                "EXTRA=%d CHANNELS=%d BYTES=%d",
                                PixelTypeToString((int) T_COLORSPACE(xform.source_type)),
                                (int) T_SWAPFIRST(xform.source_type),
                                (int) T_FLAVOR(xform.source_type),
                                (int) T_PLANAR(xform.source_type),
                                (int) T_ENDIAN16(xform.source_type),
                                (int) T_DOSWAP(xform.source_type),
                                (int) T_EXTRA(xform.source_type),
                                (int) T_CHANNELS(xform.source_type),
                                (int) T_BYTES(xform.source_type));

          (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                "Target pixel format: COLORSPACE=%s SWAPFIRST=%d "
                                "FLAVOR=%d PLANAR=%d ENDIAN16=%d DOSWAP=%d "
                                "EXTRA=%d CHANNELS=%d BYTES=%d",
                                PixelTypeToString((int) T_COLORSPACE(xform.target_type)),
                                (int) T_SWAPFIRST(xform.target_type),
                                (int) T_FLAVOR(xform.target_type),
                                (int) T_PLANAR(xform.target_type),
                                (int) T_ENDIAN16(xform.target_type),
                                (int) T_DOSWAP(xform.target_type),
                                (int) T_EXTRA(xform.target_type),
                                (int) T_CHANNELS(xform.target_type),
                                (int) T_BYTES(xform.target_type));

          switch (image->rendering_intent)
            {
            case AbsoluteIntent:
              xform.intent=INTENT_ABSOLUTE_COLORIMETRIC;
              break;
            case PerceptualIntent:
              xform.intent=INTENT_PERCEPTUAL;
              break;
            case RelativeIntent:
              xform.intent=INTENT_RELATIVE_COLORIMETRIC;
              break;
            case SaturationIntent:
              xform.intent=INTENT_SATURATION;
              break;
            default:
              xform.intent=INTENT_PERCEPTUAL;
              break;
            }

          /*
            Transform just the colormap if the image is colormapped and we're
            not transforming from gray to RGB/CMYK. A gray to RGB/CMYK
            transformation must create a direct class image for the new image
            to match the color profile even if the new image only has gray
            colors. CMYK images are never color mapped.
          */
          transform_colormap=(image->storage_class == PseudoClass) &&
            (xform.target_colorspace != CMYKColorspace) &&
            ((xform.source_colorspace != GRAYColorspace) ||
             (xform.source_colorspace == xform.target_colorspace));

          /* build pre-computed transforms? */
          xform.flags=(transform_colormap ? cmsFLAGS_NOOPTIMIZE : 0);

          xform.transform=AllocateThreadViewDataSet(MagickFreeCMSTransform,
                                                    image,&image->exception);
          if (xform.transform == (ThreadViewDataSet *) NULL)
            status=MagickFail;
          if (status != MagickFail)
            {
              cmsHTRANSFORM
                transform;

              unsigned int
                index;

              for (index=0 ; index < GetThreadViewDataSetAllocatedViews(xform.transform); index++)
                {
                  transform=cmsCreateTransformTHR((cmsContext) &xform,/* transform handle */
                                               xform.source_profile,  /* input profile */
                                               xform.source_type,     /* input pixel format */
                                               xform.target_profile,  /* output profile */
                                               xform.target_type,     /* output pixel format */
                                               xform.intent,          /* rendering intent */
                                               xform.flags            /* pre-computed transforms? */
                                               );
                  if (transform == (cmsHTRANSFORM) NULL)
                    {
                      status=MagickFail;
                      break;
                    }
                  AssignThreadViewData(xform.transform,index,transform);
                }
            }
          (void) cmsCloseProfile(xform.source_profile);
          (void) cmsCloseProfile(xform.target_profile);
          if (status == MagickFail)
            {
              DestroyThreadViewDataSet(xform.transform);
              ThrowBinaryException3(ResourceLimitError,UnableToManageColor,
                                    UnableToCreateColorTransform);
            }

          if (transform_colormap)
            {
              (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                    "Performing pseudo class color conversion");

              (void) ProfileImagePixels(NULL,
                                        &xform,
                                        image,
                                        image->colormap,
                                        (IndexPacket *) NULL,
                                        image->colors,
                                        &image->exception);

              (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                    "Completed pseudo class color conversion");
              status &= SyncImage(image);
            }
          else
            {
              (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                    "Performing direct class color conversion");
              if (image->storage_class == PseudoClass)
                {
                  status &= SyncImage(image);
                  image->storage_class=DirectClass;
                }
              if (xform.target_colorspace == CMYKColorspace)
                image->colorspace=xform.target_colorspace;

              status=PixelIterateMonoModify(ProfileImagePixels,
                                            NULL,
                                            ProfileImageText,
                                            NULL,&xform,0,0,image->columns,image->rows,
                                            image,&image->exception);

              (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                                    "Completed direct class color conversion");

            }
          image->colorspace=xform.target_colorspace;
          /*
            We can't be sure black and white stays exactly black and white
            and that gray colors transform to gray colors.
          */
          image->is_grayscale=IsGrayColorspace(xform.target_colorspace);
          image->is_monochrome=False;
          DestroyThreadViewDataSet(xform.transform);

          /*
            Throw away the old profile after conversion before we
            assign a new one.
          */
          DeleteImageProfile(image,"ICM");
#else
          ThrowBinaryException(MissingDelegateError,LCMSLibraryIsNotAvailable,
                               image->filename);
#endif
        }

      /*
        TODO: If the image *did not* already have a color profile,
        verify that the colorspace of the new profile is valid for the
        colorspace of the image. If LCMS is not available we should
        refuse to assign a new profile (just like we're refusing a
        conversion above) as we can't be sure the assigment is valid.
        We might be trying to assign a CMYK profile to an RGB image,
        for instance.
      */

      (void) SetImageProfile(image,"ICM",profile,length);
      if (!clone)
        MagickFreeMemory(profile);
      return(status);
    }

  status &= SetImageProfile(image,name,profile,length);
  if (!clone)
    MagickFreeMemory(profile);

  return(status);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%     S e t I m a g e P r o f i l e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  SetImageProfile adds a named profile to the image. If a profile with the
%  same name already exists, then it is replaced. If a null profile address
%  is supplied, then an existing profile is removed. The profile is copied
%  into the image. Note that this function does not execute CMS color
%  profiles. Any existing CMS color profile is simply replaced. Use the
%  ProfileImage() function in order to execute a CMS color profile.
%
%  Older versions of this function stored profiles named "8BIM" and "IPTC"
%  in the same storage location.  This is no longer the case.  However,
%  GetImageProfile() will try the alternate name if the specifically
%  requested profile name is not available.  Note that when trying to remove
%  a profile, it may be necessary to remove both names in order for an
%  "IPTC" profile to no longer be included in output file formats.
%
%  The format of the SetImageProfile method is:
%
%      unsigned int SetImageProfile(Image *image,const char *name,
%                            const unsigned char *profile,const size_t length)
%
%  A description of each parameter follows:
%
%    o image: The image.
%
%    o name: Profile name. Valid names are "8BIM", "ICM", "IPTC", XMP, or any
%                          unique text string.
%
%    o profile: Address of profile to add. Pass zero to remove an existing
%               profile.
%
%    o length: The length of the profile.
%
*/
MagickExport MagickPassFail
SetImageProfile(Image *image,const char *name, const unsigned char *profile,
                const size_t length)
{
  char
    ucase_name[MaxTextExtent];

  unsigned int
    status = MagickPass;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  assert(name != NULL);

  if (strlcpy(ucase_name,name,sizeof(ucase_name)) >= sizeof(ucase_name))
    {
      (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                            "Profile name too long! (%s)",name);
      return MagickFail;
    }
  LocaleUpper(ucase_name);

  if ((profile == 0) && (image->profiles != 0))
    {
      /*
        Remove existing entry.
      */
      (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                            "Removing %s profile",name);
      status &= MagickMapRemoveEntry(image->profiles,name);
    }
  else
    {
      /*
        Add or replace entry.
      */
      if (image->profiles == 0)
        image->profiles=MagickMapAllocateMap(MagickMapCopyBlob,
                                             MagickMapDeallocateBlob);

      if (image->profiles == 0)
        ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
                              UnableToAddOrRemoveProfile);

      (void) LogMagickEvent(TransformEvent,GetMagickModule(),
                            "Adding %s profile with length %ld bytes",name,
                            (unsigned long) length);
      if (profile != 0)
        {
          status &= MagickMapAddEntry(image->profiles,name,profile,length,
                                      &image->exception);
        }
    }
  return (status);
}