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