]> granicus.if.org Git - imagemagick/blob - coders/tga.c
https://github.com/ImageMagick/ImageMagick/issues/1286
[imagemagick] / coders / tga.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            TTTTT   GGGG   AAA                               %
7 %                              T    G      A   A                              %
8 %                              T    G  GG  AAAAA                              %
9 %                              T    G   G  A   A                              %
10 %                              T     GGG   A   A                              %
11 %                                                                             %
12 %                                                                             %
13 %                    Read/Write Truevision Targa Image Format                 %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    https://www.imagemagick.org/script/license.php                           %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/artifact.h"
44 #include "MagickCore/attribute.h"
45 #include "MagickCore/blob.h"
46 #include "MagickCore/blob-private.h"
47 #include "MagickCore/cache.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colormap-private.h"
51 #include "MagickCore/colorspace.h"
52 #include "MagickCore/colorspace-private.h"
53 #include "MagickCore/exception.h"
54 #include "MagickCore/exception-private.h"
55 #include "MagickCore/image.h"
56 #include "MagickCore/image-private.h"
57 #include "MagickCore/list.h"
58 #include "MagickCore/magick.h"
59 #include "MagickCore/memory_.h"
60 #include "MagickCore/monitor.h"
61 #include "MagickCore/monitor-private.h"
62 #include "MagickCore/option.h"
63 #include "MagickCore/pixel-accessor.h"
64 #include "MagickCore/property.h"
65 #include "MagickCore/quantum-private.h"
66 #include "MagickCore/static.h"
67 #include "MagickCore/string_.h"
68 #include "MagickCore/module.h"
69
70 /*
71   Enumerated declaractions.
72 */
73 typedef enum
74 {
75   TGAColormap = 1,
76   TGARGB = 2,
77   TGAMonochrome = 3,
78   TGARLEColormap = 9,
79   TGARLERGB = 10,
80   TGARLEMonochrome = 11
81 } TGAImageType;
82
83 /*
84   Typedef declaractions.
85 */
86 typedef struct _TGAInfo
87 {
88   TGAImageType
89     image_type;
90
91   unsigned char
92     id_length,
93     colormap_type;
94
95   unsigned short
96     colormap_index,
97     colormap_length;
98
99   unsigned char
100     colormap_size;
101
102   unsigned short
103     x_origin,
104     y_origin,
105     width,
106     height;
107
108   unsigned char
109     bits_per_pixel,
110     attributes;
111 } TGAInfo;
112 \f
113 /*
114   Forward declarations.
115 */
116 static MagickBooleanType
117   WriteTGAImage(const ImageInfo *,Image *,ExceptionInfo *);
118 \f
119 /*
120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121 %                                                                             %
122 %                                                                             %
123 %                                                                             %
124 %   R e a d T G A I m a g e                                                   %
125 %                                                                             %
126 %                                                                             %
127 %                                                                             %
128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
129 %
130 %  ReadTGAImage() reads a Truevision TGA image file and returns it.
131 %  It allocates the memory necessary for the new Image structure and returns
132 %  a pointer to the new image.
133 %
134 %  The format of the ReadTGAImage method is:
135 %
136 %      Image *ReadTGAImage(const ImageInfo *image_info,ExceptionInfo *exception)
137 %
138 %  A description of each parameter follows:
139 %
140 %    o image_info: the image info.
141 %
142 %    o exception: return any errors or warnings in this structure.
143 %
144 */
145 static Image *ReadTGAImage(const ImageInfo *image_info,
146   ExceptionInfo *exception)
147 {
148   Image
149     *image;
150
151   MagickBooleanType
152     status;
153
154   PixelInfo
155     pixel;
156
157   Quantum
158     index;
159
160   register Quantum
161     *q;
162
163   register ssize_t
164     i,
165     x;
166
167   size_t
168     base,
169     flag,
170     offset,
171     real,
172     skip;
173
174   ssize_t
175     count,
176     y;
177
178   TGAInfo
179     tga_info;
180
181   unsigned char
182     j,
183     k,
184     pixels[4],
185     runlength;
186
187   unsigned int
188     alpha_bits;
189
190   /*
191     Open image file.
192   */
193   assert(image_info != (const ImageInfo *) NULL);
194   assert(image_info->signature == MagickCoreSignature);
195   if (image_info->debug != MagickFalse)
196     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
197       image_info->filename);
198   assert(exception != (ExceptionInfo *) NULL);
199   assert(exception->signature == MagickCoreSignature);
200   image=AcquireImage(image_info,exception);
201   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
202   if (status == MagickFalse)
203     {
204       image=DestroyImageList(image);
205       return((Image *) NULL);
206     }
207   /*
208     Read TGA header information.
209   */
210   count=ReadBlob(image,1,&tga_info.id_length);
211   tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
212   tga_info.image_type=(TGAImageType) ReadBlobByte(image);
213   if ((count != 1) ||
214       ((tga_info.image_type != TGAColormap) &&
215        (tga_info.image_type != TGARGB) &&
216        (tga_info.image_type != TGAMonochrome) &&
217        (tga_info.image_type != TGARLEColormap) &&
218        (tga_info.image_type != TGARLERGB) &&
219        (tga_info.image_type != TGARLEMonochrome)) ||
220       (((tga_info.image_type == TGAColormap) ||
221        (tga_info.image_type == TGARLEColormap)) &&
222        (tga_info.colormap_type == 0)))
223     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
224   tga_info.colormap_index=ReadBlobLSBShort(image);
225   tga_info.colormap_length=ReadBlobLSBShort(image);
226   tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
227   tga_info.x_origin=ReadBlobLSBShort(image);
228   tga_info.y_origin=ReadBlobLSBShort(image);
229   tga_info.width=(unsigned short) ReadBlobLSBShort(image);
230   tga_info.height=(unsigned short) ReadBlobLSBShort(image);
231   tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
232   tga_info.attributes=(unsigned char) ReadBlobByte(image);
233   if (EOFBlob(image) != MagickFalse)
234     ThrowReaderException(CorruptImageError,"UnableToReadImageData");
235   if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
236        (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
237     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
238   /*
239     Initialize image structure.
240   */
241   image->columns=tga_info.width;
242   image->rows=tga_info.height;
243   alpha_bits=(tga_info.attributes & 0x0FU);
244   image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
245     (tga_info.colormap_size == 32) ?  BlendPixelTrait : UndefinedPixelTrait;
246   if ((tga_info.image_type != TGAColormap) &&
247       (tga_info.image_type != TGARLEColormap))
248     image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
249       (tga_info.bits_per_pixel <= 16) ? 5 : 8);
250   else
251     image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
252       (tga_info.colormap_size <= 16) ? 5 : 8);
253   if ((tga_info.image_type == TGAColormap) ||
254       (tga_info.image_type == TGAMonochrome) ||
255       (tga_info.image_type == TGARLEColormap) ||
256       (tga_info.image_type == TGARLEMonochrome))
257     image->storage_class=PseudoClass;
258   image->compression=NoCompression;
259   if ((tga_info.image_type == TGARLEColormap) ||
260       (tga_info.image_type == TGARLEMonochrome) ||
261       (tga_info.image_type == TGARLERGB))
262     image->compression=RLECompression;
263   if (image->storage_class == PseudoClass)
264     {
265       if (tga_info.colormap_type != 0)
266         image->colors=tga_info.colormap_index+tga_info.colormap_length;
267       else
268         {
269           size_t
270             one;
271
272           one=1;
273           image->colors=one << tga_info.bits_per_pixel;
274           if (image->colors > GetBlobSize(image))
275             ThrowReaderException(CorruptImageError,
276               "InsufficientImageDataInFile");
277           if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
278             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
279         }
280     }
281   if (tga_info.id_length != 0)
282     {
283       char
284         *comment;
285
286       size_t
287         length;
288
289       /*
290         TGA image comment.
291       */
292       length=(size_t) tga_info.id_length;
293       comment=(char *) NULL;
294       if (~length >= (MagickPathExtent-1))
295         comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,
296           sizeof(*comment));
297       if (comment == (char *) NULL)
298         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
299       count=ReadBlob(image,length,(unsigned char *) comment);
300       if (count == (ssize_t) length)
301         {
302           comment[length]='\0';
303           (void) SetImageProperty(image,"comment",comment,exception);
304         }
305       comment=DestroyString(comment);
306     }
307   if (tga_info.attributes & (1UL << 4))
308     {
309       if (tga_info.attributes & (1UL << 5))
310         SetImageArtifact(image,"tga:image-origin","TopRight");
311       else
312         SetImageArtifact(image,"tga:image-origin","BottomRight");
313     }
314   else
315     {
316       if (tga_info.attributes & (1UL << 5))
317         SetImageArtifact(image,"tga:image-origin","TopLeft");
318       else
319         SetImageArtifact(image,"tga:image-origin","BottomLeft");
320     }
321   if (image_info->ping != MagickFalse)
322     {
323       (void) CloseBlob(image);
324       return(image);
325     }
326   status=SetImageExtent(image,image->columns,image->rows,exception);
327   if (status == MagickFalse)
328     return(DestroyImageList(image));
329   (void) memset(&pixel,0,sizeof(pixel));
330   pixel.alpha=(MagickRealType) OpaqueAlpha;
331   if (tga_info.colormap_type != 0)
332     {
333       /*
334         Read TGA raster colormap.
335       */
336       if (image->colors < tga_info.colormap_index)
337         image->colors=tga_info.colormap_index;
338       if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
339         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
340       for (i=0; i < (ssize_t) tga_info.colormap_index; i++)
341         image->colormap[i]=pixel;
342       for ( ; i < (ssize_t) image->colors; i++)
343       {
344         switch (tga_info.colormap_size)
345         {
346           case 8:
347           default:
348           {
349             /*
350               Gray scale.
351             */
352             pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
353               ReadBlobByte(image));
354             pixel.green=pixel.red;
355             pixel.blue=pixel.red;
356             break;
357           }
358           case 15:
359           case 16:
360           {
361             QuantumAny
362               range;
363
364             /*
365               5 bits each of red green and blue.
366             */
367             j=(unsigned char) ReadBlobByte(image);
368             k=(unsigned char) ReadBlobByte(image);
369             range=GetQuantumRange(5UL);
370             pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
371               range);
372             pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)
373               << 3)+(1UL*(j & 0xe0) >> 5),range);
374             pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
375             break;
376           }
377           case 24:
378           {
379             /*
380               8 bits each of blue, green and red.
381             */
382             pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
383               ReadBlobByte(image));
384             pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
385               ReadBlobByte(image));
386             pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
387               ReadBlobByte(image));
388             break;
389           }
390           case 32:
391           {
392             /*
393               8 bits each of blue, green, red, and alpha.
394             */
395             pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
396               ReadBlobByte(image));
397             pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
398               ReadBlobByte(image));
399             pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
400               ReadBlobByte(image));
401             pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)
402               ReadBlobByte(image));
403             break;
404           }
405         }
406         image->colormap[i]=pixel;
407       }
408     }
409   /*
410     Convert TGA pixels to pixel packets.
411   */
412   base=0;
413   flag=0;
414   skip=MagickFalse;
415   real=0;
416   index=0;
417   runlength=0;
418   offset=0;
419   for (y=0; y < (ssize_t) image->rows; y++)
420   {
421     real=offset;
422     if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
423       real=image->rows-real-1;
424     q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
425     if (q == (Quantum *) NULL)
426       break;
427     for (x=0; x < (ssize_t) image->columns; x++)
428     {
429       if ((tga_info.image_type == TGARLEColormap) ||
430           (tga_info.image_type == TGARLERGB) ||
431           (tga_info.image_type == TGARLEMonochrome))
432         {
433           if (runlength != 0)
434             {
435               runlength--;
436               skip=flag != 0;
437             }
438           else
439             {
440               count=ReadBlob(image,1,&runlength);
441               if (count != 1)
442                 ThrowReaderException(CorruptImageError,"UnableToReadImageData");
443               flag=runlength & 0x80;
444               if (flag != 0)
445                 runlength-=128;
446               skip=MagickFalse;
447             }
448         }
449       if (skip == MagickFalse)
450         switch (tga_info.bits_per_pixel)
451         {
452           case 8:
453           default:
454           {
455             /*
456               Gray scale.
457             */
458             if (ReadBlob(image,1,pixels) != 1)
459               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
460             index=(Quantum) pixels[0];
461             if (tga_info.colormap_type != 0)
462               pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
463                 (ssize_t) index,exception)];
464             else
465               {
466                 pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
467                   index);
468                 pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
469                   index);
470                 pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
471                   index);
472               }
473             break;
474           }
475           case 15:
476           case 16:
477           {
478             QuantumAny
479               range;
480
481             /*
482               5 bits each of RGB.
483             */
484             if (ReadBlob(image,2,pixels) != 2)
485               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
486             j=pixels[0];
487             k=pixels[1];
488             range=GetQuantumRange(5UL);
489             pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
490               range);
491             pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*
492               (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);
493             pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
494             if (image->alpha_trait != UndefinedPixelTrait)
495               pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)
496                 TransparentAlpha : (Quantum) OpaqueAlpha);
497             if (image->storage_class == PseudoClass)
498               index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+
499                 j,exception);
500             break;
501           }
502           case 24:
503           {
504             /*
505               BGR pixels.
506             */
507             if (ReadBlob(image,3,pixels) != 3)
508               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
509             pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
510             pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
511             pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
512             break;
513           }
514           case 32:
515           {
516             /*
517               BGRA pixels.
518             */
519             if (ReadBlob(image,4,pixels) != 4)
520               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
521             pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
522             pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
523             pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
524             pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);
525             break;
526           }
527         }
528       if (status == MagickFalse)
529         ThrowReaderException(CorruptImageError,"UnableToReadImageData");
530       if (image->storage_class == PseudoClass)
531         SetPixelIndex(image,index,q);
532       SetPixelRed(image,ClampToQuantum(pixel.red),q);
533       SetPixelGreen(image,ClampToQuantum(pixel.green),q);
534       SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
535       if (image->alpha_trait != UndefinedPixelTrait)
536         SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
537       q+=GetPixelChannels(image);
538     }
539     /*
540       if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)
541         offset+=4;
542       else
543     */
544       if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)
545         offset+=2;
546       else
547         offset++;
548     if (offset >= image->rows)
549       {
550         base++;
551         offset=base;
552       }
553     if (SyncAuthenticPixels(image,exception) == MagickFalse)
554       break;
555     if (image->previous == (Image *) NULL)
556       {
557         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
558           image->rows);
559         if (status == MagickFalse)
560           break;
561       }
562   }
563   if (EOFBlob(image) != MagickFalse)
564     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
565       image->filename);
566   (void) CloseBlob(image);
567   return(GetFirstImageInList(image));
568 }
569 \f
570 /*
571 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
572 %                                                                             %
573 %                                                                             %
574 %                                                                             %
575 %   R e g i s t e r T G A I m a g e                                           %
576 %                                                                             %
577 %                                                                             %
578 %                                                                             %
579 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
580 %
581 %  RegisterTGAImage() adds properties for the TGA image format to
582 %  the list of supported formats.  The properties include the image format
583 %  tag, a method to read and/or write the format, whether the format
584 %  supports the saving of more than one frame to the same file or blob,
585 %  whether the format supports native in-memory I/O, and a brief
586 %  description of the format.
587 %
588 %  The format of the RegisterTGAImage method is:
589 %
590 %      size_t RegisterTGAImage(void)
591 %
592 */
593 ModuleExport size_t RegisterTGAImage(void)
594 {
595   MagickInfo
596     *entry;
597
598   entry=AcquireMagickInfo("TGA","ICB","Truevision Targa image");
599   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
600   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
601   entry->flags|=CoderDecoderSeekableStreamFlag;
602   entry->flags^=CoderAdjoinFlag;
603   (void) RegisterMagickInfo(entry);
604   entry=AcquireMagickInfo("TGA","TGA","Truevision Targa image");
605   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
606   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
607   entry->flags|=CoderDecoderSeekableStreamFlag;
608   entry->flags^=CoderAdjoinFlag;
609   (void) RegisterMagickInfo(entry);
610   entry=AcquireMagickInfo("TGA","VDA","Truevision Targa image");
611   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
612   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
613   entry->flags|=CoderDecoderSeekableStreamFlag;
614   entry->flags^=CoderAdjoinFlag;
615   (void) RegisterMagickInfo(entry);
616   entry=AcquireMagickInfo("TGA","VST","Truevision Targa image");
617   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
618   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
619   entry->flags|=CoderDecoderSeekableStreamFlag;
620   entry->flags^=CoderAdjoinFlag;
621   (void) RegisterMagickInfo(entry);
622   return(MagickImageCoderSignature);
623 }
624 \f
625 /*
626 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
627 %                                                                             %
628 %                                                                             %
629 %                                                                             %
630 %   U n r e g i s t e r T G A I m a g e                                       %
631 %                                                                             %
632 %                                                                             %
633 %                                                                             %
634 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
635 %
636 %  UnregisterTGAImage() removes format registrations made by the
637 %  TGA module from the list of supported formats.
638 %
639 %  The format of the UnregisterTGAImage method is:
640 %
641 %      UnregisterTGAImage(void)
642 %
643 */
644 ModuleExport void UnregisterTGAImage(void)
645 {
646   (void) UnregisterMagickInfo("ICB");
647   (void) UnregisterMagickInfo("TGA");
648   (void) UnregisterMagickInfo("VDA");
649   (void) UnregisterMagickInfo("VST");
650 }
651 \f
652 /*
653 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
654 %                                                                             %
655 %                                                                             %
656 %                                                                             %
657 %   W r i t e T G A I m a g e                                                 %
658 %                                                                             %
659 %                                                                             %
660 %                                                                             %
661 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
662 %
663 %  WriteTGAImage() writes a image in the Truevision Targa rasterfile
664 %  format.
665 %
666 %  The format of the WriteTGAImage method is:
667 %
668 %      MagickBooleanType WriteTGAImage(const ImageInfo *image_info,
669 %        Image *image,ExceptionInfo *exception)
670 %
671 %  A description of each parameter follows.
672 %
673 %    o image_info: the image info.
674 %
675 %    o image:  The image.
676 %
677 */
678 static inline void WriteTGAPixel(Image *image,TGAImageType image_type,
679   const Quantum *p,const QuantumAny range,const double midpoint)
680 {
681   if (image_type == TGAColormap || image_type == TGARLEColormap)
682     (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p));
683   else
684     {
685       if (image_type == TGAMonochrome || image_type == TGARLEMonochrome)
686         (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
687           GetPixelLuma(image,p))));
688       else
689         if (image->depth == 5)
690           {
691             unsigned char
692               green,
693               value;
694
695             green=(unsigned char) ScaleQuantumToAny(GetPixelGreen(image,p),
696               range);
697             value=((unsigned char) ScaleQuantumToAny(GetPixelBlue(image,p),
698               range)) | ((green & 0x07) << 5);
699             (void) WriteBlobByte(image,value);
700             value=(((image->alpha_trait != UndefinedPixelTrait) &&
701               ((double) GetPixelAlpha(image,p) > midpoint)) ? 0x80 : 0) |
702               ((unsigned char) ScaleQuantumToAny(GetPixelRed(image,p),range) <<
703               2) | ((green & 0x18) >> 3);
704             (void) WriteBlobByte(image,value);
705           }
706         else
707           {
708             (void) WriteBlobByte(image,ScaleQuantumToChar(
709               GetPixelBlue(image,p)));
710             (void) WriteBlobByte(image,ScaleQuantumToChar(
711               GetPixelGreen(image,p)));
712             (void) WriteBlobByte(image,ScaleQuantumToChar(
713               GetPixelRed(image,p)));
714             if (image->alpha_trait != UndefinedPixelTrait)
715               (void) WriteBlobByte(image,ScaleQuantumToChar(
716                 GetPixelAlpha(image,p)));
717           }
718     }
719 }
720
721 static MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image,
722   ExceptionInfo *exception)
723 {
724   CompressionType
725     compression;
726
727   const char
728     *comment,
729     *value;
730
731   const double
732     midpoint = QuantumRange/2.0;
733
734   MagickBooleanType
735     status;
736
737   QuantumAny
738     range;
739
740   register const Quantum
741     *p;
742
743   register ssize_t
744     x;
745
746   register ssize_t
747     i;
748
749   register unsigned char
750     *q;
751
752   size_t
753     channels;
754
755   ssize_t
756     count,
757     y;
758
759   TGAInfo
760     tga_info;
761
762   /*
763     Open output image file.
764   */
765   assert(image_info != (const ImageInfo *) NULL);
766   assert(image_info->signature == MagickCoreSignature);
767   assert(image != (Image *) NULL);
768   assert(image->signature == MagickCoreSignature);
769   if (image->debug != MagickFalse)
770     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
771   assert(exception != (ExceptionInfo *) NULL);
772   assert(exception->signature == MagickCoreSignature);
773   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
774   if (status == MagickFalse)
775     return(status);
776   /*
777     Initialize TGA raster file header.
778   */
779   if ((image->columns > 65535L) || (image->rows > 65535L))
780     ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
781   (void) TransformImageColorspace(image,sRGBColorspace,exception);
782   compression=image->compression;
783   if (image_info->compression != UndefinedCompression)
784     compression=image_info->compression;
785   range=GetQuantumRange(5UL);
786   tga_info.id_length=0;
787   comment=GetImageProperty(image,"comment",exception);
788   if (comment != (const char *) NULL)
789     tga_info.id_length=(unsigned char) MagickMin(strlen(comment),255);
790   tga_info.colormap_type=0;
791   tga_info.colormap_index=0;
792   tga_info.colormap_length=0;
793   tga_info.colormap_size=0;
794   tga_info.x_origin=0;
795   tga_info.y_origin=0;
796   tga_info.width=(unsigned short) image->columns;
797   tga_info.height=(unsigned short) image->rows;
798   tga_info.bits_per_pixel=8;
799   tga_info.attributes=0;
800   if ((image_info->type != TrueColorType) &&
801       (image_info->type != TrueColorAlphaType) &&
802       (image_info->type != PaletteType) &&
803       (image->alpha_trait == UndefinedPixelTrait) &&
804       (SetImageGray(image,exception) != MagickFalse))
805     tga_info.image_type=compression == RLECompression ? TGARLEMonochrome :
806       TGAMonochrome;
807   else
808     if ((image->storage_class == DirectClass) || (image->colors > 256))
809       {
810         /*
811           Full color TGA raster.
812         */
813         tga_info.image_type=compression == RLECompression ? TGARLERGB : TGARGB;
814         if (image_info->depth == 5)
815           {
816             tga_info.bits_per_pixel=16;
817             if (image->alpha_trait != UndefinedPixelTrait)
818               tga_info.attributes=1;  /* # of alpha bits */
819           }
820         else
821           {
822             tga_info.bits_per_pixel=24;
823             if (image->alpha_trait != UndefinedPixelTrait)
824               {
825                 tga_info.bits_per_pixel=32;
826                 tga_info.attributes=8;  /* # of alpha bits */
827               }
828           }
829       }
830     else
831       {
832         /*
833           Colormapped TGA raster.
834         */
835         tga_info.image_type=compression == RLECompression ? TGARLEColormap :
836           TGAColormap;
837         tga_info.colormap_type=1;
838         tga_info.colormap_length=(unsigned short) image->colors;
839         if (image_info->depth == 5)
840           tga_info.colormap_size=16;
841         else
842           tga_info.colormap_size=24;
843       }
844   value=GetImageArtifact(image,"tga:image-origin");
845   if (value != (const char *) NULL)
846     {
847       OrientationType
848         origin;
849
850       origin=(OrientationType) ParseCommandOption(MagickOrientationOptions,
851         MagickFalse,value);
852       if (origin == BottomRightOrientation || origin == TopRightOrientation)
853         tga_info.attributes|=(1UL << 4);
854       if (origin == TopLeftOrientation || origin == TopRightOrientation)
855         tga_info.attributes|=(1UL << 5);
856     }
857   /*
858     Write TGA header.
859   */
860   (void) WriteBlobByte(image,tga_info.id_length);
861   (void) WriteBlobByte(image,tga_info.colormap_type);
862   (void) WriteBlobByte(image,(unsigned char) tga_info.image_type);
863   (void) WriteBlobLSBShort(image,tga_info.colormap_index);
864   (void) WriteBlobLSBShort(image,tga_info.colormap_length);
865   (void) WriteBlobByte(image,tga_info.colormap_size);
866   (void) WriteBlobLSBShort(image,tga_info.x_origin);
867   (void) WriteBlobLSBShort(image,tga_info.y_origin);
868   (void) WriteBlobLSBShort(image,tga_info.width);
869   (void) WriteBlobLSBShort(image,tga_info.height);
870   (void) WriteBlobByte(image,tga_info.bits_per_pixel);
871   (void) WriteBlobByte(image,tga_info.attributes);
872   if (tga_info.id_length != 0)
873     (void) WriteBlob(image,tga_info.id_length,(unsigned char *) comment);
874   if (tga_info.colormap_type != 0)
875     {
876       unsigned char
877         green,
878         *targa_colormap;
879
880       /*
881         Dump colormap to file (blue, green, red byte order).
882       */
883       targa_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
884         tga_info.colormap_length,(tga_info.colormap_size/8)*
885         sizeof(*targa_colormap));
886       if (targa_colormap == (unsigned char *) NULL)
887         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
888       q=targa_colormap;
889       for (i=0; i < (ssize_t) image->colors; i++)
890       {
891         if (image_info->depth == 5)
892           {
893             green=(unsigned char) ScaleQuantumToAny(ClampToQuantum(
894               image->colormap[i].green),range);
895             *q++=((unsigned char) ScaleQuantumToAny(ClampToQuantum(
896               image->colormap[i].blue),range)) | ((green & 0x07) << 5);
897             *q++=(((image->alpha_trait != UndefinedPixelTrait) && ((double)
898               ClampToQuantum(image->colormap[i].alpha) > midpoint)) ? 0x80 : 0) |
899               ((unsigned char) ScaleQuantumToAny(ClampToQuantum(
900               image->colormap[i].red),range) << 2) | ((green & 0x18) >> 3);
901           }
902         else
903           {
904             *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
905             *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
906             *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
907           }
908       }
909       (void) WriteBlob(image,(size_t) ((tga_info.colormap_size/8)*
910         tga_info.colormap_length),targa_colormap);
911       targa_colormap=(unsigned char *) RelinquishMagickMemory(targa_colormap);
912     }
913   /*
914     Convert MIFF to TGA raster pixels.
915   */
916   channels=GetPixelChannels(image);
917   for (y=(ssize_t) (image->rows-1); y >= 0; y--)
918   {
919     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
920     if (p == (const Quantum *) NULL)
921       break;
922     if (compression == RLECompression)
923       {
924         x=0;
925         count=0;
926         while (x < (ssize_t) image->columns)
927         {
928           i=1;
929           while ((i < 128) && (count + i < 128) &&
930                  ((x + i) < (ssize_t) image->columns))
931           {
932             if (tga_info.image_type == TGARLEColormap)
933               {
934                 if (GetPixelIndex(image,p+(i*channels)) !=
935                     GetPixelIndex(image,p+((i-1)*channels)))
936                   break;
937               }
938             else if (tga_info.image_type == TGARLEMonochrome)
939               {
940                 if (GetPixelLuma(image,p+(i*channels)) !=
941                     GetPixelLuma(image,p+((i-1)*channels)))
942                   break;
943               }
944             else
945               {
946                 if ((GetPixelBlue(image,p+(i*channels)) !=
947                      GetPixelBlue(image,p+((i-1)*channels))) ||
948                     (GetPixelGreen(image,p+(i*channels)) !=
949                      GetPixelGreen(image,p+((i-1)*channels))) ||
950                     (GetPixelRed(image,p+(i*channels)) !=
951                      GetPixelRed(image,p+((i-1)*channels))))
952                   break;
953                 if ((image->alpha_trait != UndefinedPixelTrait) &&
954                     (GetPixelAlpha(image,p+(i*channels)) !=
955                      GetPixelAlpha(image,p+(i-1)*channels)))
956                   break;
957               }
958             i++;
959           }
960           if (i < 3)
961             {
962               count+=i;
963               p+=(i*channels);
964             }
965           if ((i >= 3) || (count == 128) ||
966               ((x + i) == (ssize_t) image->columns))
967             {
968               if (count > 0)
969                 {
970                   (void) WriteBlobByte(image,(unsigned char) (--count));
971                   while (count >= 0)
972                   {
973                     WriteTGAPixel(image,tga_info.image_type,p-((count+1)*
974                       channels),range,midpoint);
975                     count--;
976                   }
977                   count=0;
978                 }
979             }
980           if (i >= 3)
981             {
982               (void) WriteBlobByte(image,(unsigned char) ((i-1) | 0x80));
983               WriteTGAPixel(image,tga_info.image_type,p,range,midpoint);
984               p+=(i*channels);
985             }
986           x+=i;
987         }
988       }
989     else
990       {
991         for (x=0; x < (ssize_t) image->columns; x++)
992           {
993             WriteTGAPixel(image,tga_info.image_type,p,range,midpoint);
994             p+=channels;
995           }
996       }
997     if (image->previous == (Image *) NULL)
998       {
999         status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1000           image->rows);
1001         if (status == MagickFalse)
1002           break;
1003       }
1004   }
1005   (void) CloseBlob(image);
1006   return(MagickTrue);
1007 }