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