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