]> granicus.if.org Git - imagemagick/blob - coders/tga.c
(no commit message)
[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 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2013 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 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/color-private.h"
48 #include "MagickCore/colormap.h"
49 #include "MagickCore/colormap-private.h"
50 #include "MagickCore/colorspace.h"
51 #include "MagickCore/colorspace-private.h"
52 #include "MagickCore/exception.h"
53 #include "MagickCore/exception-private.h"
54 #include "MagickCore/image.h"
55 #include "MagickCore/image-private.h"
56 #include "MagickCore/list.h"
57 #include "MagickCore/magick.h"
58 #include "MagickCore/memory_.h"
59 #include "MagickCore/monitor.h"
60 #include "MagickCore/monitor-private.h"
61 #include "MagickCore/pixel-accessor.h"
62 #include "MagickCore/property.h"
63 #include "MagickCore/quantum-private.h"
64 #include "MagickCore/static.h"
65 #include "MagickCore/string_.h"
66 #include "MagickCore/module.h"
67 \f
68 /*
69   Forward declarations.
70 */
71 static MagickBooleanType
72   WriteTGAImage(const ImageInfo *,Image *,ExceptionInfo *);
73 \f
74 /*
75 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
76 %                                                                             %
77 %                                                                             %
78 %                                                                             %
79 %   R e a d T G A I m a g e                                                   %
80 %                                                                             %
81 %                                                                             %
82 %                                                                             %
83 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
84 %
85 %  ReadTGAImage() reads a Truevision TGA image file and returns it.
86 %  It allocates the memory necessary for the new Image structure and returns
87 %  a pointer to the new image.
88 %
89 %  The format of the ReadTGAImage method is:
90 %
91 %      Image *ReadTGAImage(const ImageInfo *image_info,ExceptionInfo *exception)
92 %
93 %  A description of each parameter follows:
94 %
95 %    o image_info: the image info.
96 %
97 %    o exception: return any errors or warnings in this structure.
98 %
99 */
100 static Image *ReadTGAImage(const ImageInfo *image_info,ExceptionInfo *exception)
101 {
102 #define TGAColormap 1
103 #define TGARGB 2
104 #define TGAMonochrome 3
105 #define TGARLEColormap  9
106 #define TGARLERGB  10
107 #define TGARLEMonochrome  11
108
109   typedef struct _TGAInfo
110   {
111     unsigned char
112       id_length,
113       colormap_type,
114       image_type;
115
116     unsigned short
117       colormap_index,
118       colormap_length;
119
120     unsigned char
121       colormap_size;
122
123     unsigned short
124       x_origin,
125       y_origin,
126       width,
127       height;
128
129     unsigned char
130       bits_per_pixel,
131       attributes;
132   } TGAInfo;
133
134   Image
135     *image;
136
137   MagickBooleanType
138     status;
139
140   PixelInfo
141     pixel;
142
143   Quantum
144     index;
145
146   register Quantum
147     *q;
148
149   register ssize_t
150     i,
151     x;
152
153   size_t
154     base,
155     flag,
156     offset,
157     real,
158     skip;
159
160   ssize_t
161     count,
162     y;
163
164   TGAInfo
165     tga_info;
166
167   unsigned char
168     j,
169     k,
170     pixels[4],
171     runlength;
172
173   unsigned int
174     alpha_bits;
175
176   /*
177     Open image file.
178   */
179   assert(image_info != (const ImageInfo *) NULL);
180   assert(image_info->signature == MagickSignature);
181   if (image_info->debug != MagickFalse)
182     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
183       image_info->filename);
184   assert(exception != (ExceptionInfo *) NULL);
185   assert(exception->signature == MagickSignature);
186   image=AcquireImage(image_info,exception);
187   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
188   if (status == MagickFalse)
189     {
190       image=DestroyImageList(image);
191       return((Image *) NULL);
192     }
193   /*
194     Read TGA header information.
195   */
196   count=ReadBlob(image,1,&tga_info.id_length);
197   tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
198   tga_info.image_type=(unsigned char) ReadBlobByte(image);
199   if ((count != 1) ||
200       ((tga_info.image_type != TGAColormap) &&
201        (tga_info.image_type != TGARGB) &&
202        (tga_info.image_type != TGAMonochrome) &&
203        (tga_info.image_type != TGARLEColormap) &&
204        (tga_info.image_type != TGARLERGB) &&
205        (tga_info.image_type != TGARLEMonochrome)) ||
206       (((tga_info.image_type == TGAColormap) ||
207        (tga_info.image_type == TGARLEColormap)) &&
208        (tga_info.colormap_type == 0)))
209     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
210   tga_info.colormap_index=ReadBlobLSBShort(image);
211   tga_info.colormap_length=ReadBlobLSBShort(image);
212   tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
213   tga_info.x_origin=ReadBlobLSBShort(image);
214   tga_info.y_origin=ReadBlobLSBShort(image);
215   tga_info.width=(unsigned short) ReadBlobLSBShort(image);
216   tga_info.height=(unsigned short) ReadBlobLSBShort(image);
217   tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
218   tga_info.attributes=(unsigned char) ReadBlobByte(image);
219   if (EOFBlob(image) != MagickFalse)
220     ThrowReaderException(CorruptImageError,"UnableToReadImageData");
221   if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
222        (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
223     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
224   /*
225     Initialize image structure.
226   */
227   image->columns=tga_info.width;
228   image->rows=tga_info.height;
229   alpha_bits=(tga_info.attributes & 0x0FU);
230   image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ?
231     BlendPixelTrait : UndefinedPixelTrait;
232   if ((tga_info.image_type != TGAColormap) &&
233       (tga_info.image_type != TGARLEColormap))
234     image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
235       (tga_info.bits_per_pixel <= 16) ? 5 :
236       (tga_info.bits_per_pixel == 24) ? 8 :
237       (tga_info.bits_per_pixel == 32) ? 8 : 8);
238   else
239     image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
240       (tga_info.colormap_size <= 16) ? 5 :
241       (tga_info.colormap_size == 24) ? 8 :
242       (tga_info.colormap_size == 32) ? 8 : 8);
243   if ((tga_info.image_type == TGAColormap) ||
244       (tga_info.image_type == TGAMonochrome) ||
245       (tga_info.image_type == TGARLEColormap) ||
246       (tga_info.image_type == TGARLEMonochrome))
247     image->storage_class=PseudoClass;
248   image->compression=NoCompression;
249   if ((tga_info.image_type == TGARLEColormap) ||
250       (tga_info.image_type == TGARLEMonochrome))
251     image->compression=RLECompression;
252   if (image->storage_class == PseudoClass)
253     {
254       if (tga_info.colormap_type != 0)
255         image->colors=tga_info.colormap_length;
256       else
257         {
258           size_t
259             one;
260
261           one=1;
262           image->colors=one << tga_info.bits_per_pixel;
263           if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
264             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
265         }
266     }
267   if (tga_info.id_length != 0)
268     {
269       char
270         *comment;
271
272       size_t
273         length;
274
275       /*
276         TGA image comment.
277       */
278       length=(size_t) tga_info.id_length;
279       comment=(char *) NULL;
280       if (~length >= (MaxTextExtent-1))
281         comment=(char *) AcquireQuantumMemory(length+MaxTextExtent,
282           sizeof(*comment));
283       if (comment == (char *) NULL)
284         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
285       count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
286       comment[tga_info.id_length]='\0';
287       (void) SetImageProperty(image,"comment",comment,exception);
288       comment=DestroyString(comment);
289     }
290   (void) ResetMagickMemory(&pixel,0,sizeof(pixel));
291   pixel.alpha=(MagickRealType) OpaqueAlpha;
292   if (tga_info.colormap_type != 0)
293     {
294       /*
295         Read TGA raster colormap.
296       */
297       if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
298         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
299       for (i=0; i < (ssize_t) image->colors; i++)
300       {
301         switch (tga_info.colormap_size)
302         {
303           case 8:
304           default:
305           {
306             /*
307               Gray scale.
308             */
309             pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
310               ReadBlobByte(image));
311             pixel.green=pixel.red;
312             pixel.blue=pixel.red;
313             break;
314           }
315           case 15:
316           case 16:
317           {
318             QuantumAny
319               range;
320
321             /*
322               5 bits each of red green and blue.
323             */
324             j=(unsigned char) ReadBlobByte(image);
325             k=(unsigned char) ReadBlobByte(image);
326             range=GetQuantumRange(5UL);
327             pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
328               range);
329             pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)
330               << 3)+(1UL*(j & 0xe0) >> 5),range);
331             pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
332             break;
333           }
334           case 24:
335           case 32:
336           {
337             /*
338               8 bits each of blue, green and red.
339             */
340             pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
341               ReadBlobByte(image));
342             pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
343               ReadBlobByte(image));
344             pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
345               ReadBlobByte(image));
346             break;
347           }
348         }
349         image->colormap[i]=pixel;
350       }
351     }
352   /*
353     Convert TGA pixels to pixel packets.
354   */
355   base=0;
356   flag=0;
357   skip=MagickFalse;
358   real=0;
359   index=0;
360   runlength=0;
361   offset=0;
362   for (y=0; y < (ssize_t) image->rows; y++)
363   {
364     real=offset;
365     if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
366       real=image->rows-real-1;
367     q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
368     if (q == (Quantum *) NULL)
369       break;
370     for (x=0; x < (ssize_t) image->columns; x++)
371     {
372       if ((tga_info.image_type == TGARLEColormap) ||
373           (tga_info.image_type == TGARLERGB) ||
374           (tga_info.image_type == TGARLEMonochrome))
375         {
376           if (runlength != 0)
377             {
378               runlength--;
379               skip=flag != 0;
380             }
381           else
382             {
383               count=ReadBlob(image,1,&runlength);
384               if (count == 0)
385                 ThrowReaderException(CorruptImageError,"UnableToReadImageData");
386               flag=runlength & 0x80;
387               if (flag != 0)
388                 runlength-=128;
389               skip=MagickFalse;
390             }
391         }
392       if (skip == MagickFalse)
393         switch (tga_info.bits_per_pixel)
394         {
395           case 8:
396           default:
397           {
398             /*
399               Gray scale.
400             */
401             index=(Quantum) ReadBlobByte(image);
402             if (tga_info.colormap_type != 0)
403               pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
404                 1UL*index,exception)];
405             else
406               {
407                 pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
408                   index);
409                 pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
410                   index);
411                 pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
412                   index);
413               }
414             break;
415           }
416           case 15:
417           case 16:
418           {
419             QuantumAny
420               range;
421
422             /*
423               5 bits each of RGB.
424             */
425             if (ReadBlob(image,2,pixels) != 2)
426               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
427             j=pixels[0];
428             k=pixels[1];
429             range=GetQuantumRange(5UL);
430             pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
431               range);
432             pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)
433               << 3)+(1UL*(j & 0xe0) >> 5),range);
434             pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
435             if (image->alpha_trait == BlendPixelTrait)
436               pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)
437                 OpaqueAlpha : (Quantum) TransparentAlpha); 
438             if (image->storage_class == PseudoClass)
439               index=ConstrainColormapIndex(image,((size_t) k << 8)+j,exception);
440             break;
441           }
442           case 24:
443           {
444             /*
445               BGR pixels.
446             */
447             if (ReadBlob(image,3,pixels) != 3)
448               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
449             pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
450             pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
451             pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
452             break;
453           }
454           case 32:
455           {
456             /*
457               BGRA pixels.
458             */
459             if (ReadBlob(image,4,pixels) != 4)
460               ThrowReaderException(CorruptImageError,"UnableToReadImageData");
461             pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
462             pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
463             pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
464             pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);
465             break;
466           }
467         }
468       if (status == MagickFalse)
469         ThrowReaderException(CorruptImageError,"UnableToReadImageData");
470       if (image->storage_class == PseudoClass)
471         SetPixelIndex(image,index,q);
472       SetPixelRed(image,ClampToQuantum(pixel.red),q);
473       SetPixelGreen(image,ClampToQuantum(pixel.green),q);
474       SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
475       if (image->alpha_trait == BlendPixelTrait)
476         SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
477       q+=GetPixelChannels(image);
478     }
479     if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)
480       offset+=4;
481     else
482       if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)
483         offset+=2;
484       else
485         offset++;
486     if (offset >= image->rows)
487       {
488         base++;
489         offset=base;
490       }
491     if (SyncAuthenticPixels(image,exception) == MagickFalse)
492       break;
493     if (image->previous == (Image *) NULL)
494       {
495         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
496           image->rows);
497         if (status == MagickFalse)
498           break;
499       }
500   }
501   if (EOFBlob(image) != MagickFalse)
502     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
503       image->filename);
504   (void) CloseBlob(image);
505   return(GetFirstImageInList(image));
506 }
507 \f
508 /*
509 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
510 %                                                                             %
511 %                                                                             %
512 %                                                                             %
513 %   R e g i s t e r T G A I m a g e                                           %
514 %                                                                             %
515 %                                                                             %
516 %                                                                             %
517 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
518 %
519 %  RegisterTGAImage() adds properties for the TGA image format to
520 %  the list of supported formats.  The properties include the image format
521 %  tag, a method to read and/or write the format, whether the format
522 %  supports the saving of more than one frame to the same file or blob,
523 %  whether the format supports native in-memory I/O, and a brief
524 %  description of the format.
525 %
526 %  The format of the RegisterTGAImage method is:
527 %
528 %      size_t RegisterTGAImage(void)
529 %
530 */
531 ModuleExport size_t RegisterTGAImage(void)
532 {
533   MagickInfo
534     *entry;
535
536   entry=SetMagickInfo("ICB");
537   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
538   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
539   entry->adjoin=MagickFalse;
540   entry->description=ConstantString("Truevision Targa image");
541   entry->module=ConstantString("TGA");
542   (void) RegisterMagickInfo(entry);
543   entry=SetMagickInfo("TGA");
544   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
545   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
546   entry->adjoin=MagickFalse;
547   entry->description=ConstantString("Truevision Targa image");
548   entry->module=ConstantString("TGA");
549   (void) RegisterMagickInfo(entry);
550   entry=SetMagickInfo("VDA");
551   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
552   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
553   entry->adjoin=MagickFalse;
554   entry->description=ConstantString("Truevision Targa image");
555   entry->module=ConstantString("TGA");
556   (void) RegisterMagickInfo(entry);
557   entry=SetMagickInfo("VST");
558   entry->decoder=(DecodeImageHandler *) ReadTGAImage;
559   entry->encoder=(EncodeImageHandler *) WriteTGAImage;
560   entry->adjoin=MagickFalse;
561   entry->description=ConstantString("Truevision Targa image");
562   entry->module=ConstantString("TGA");
563   (void) RegisterMagickInfo(entry);
564   return(MagickImageCoderSignature);
565 }
566 \f
567 /*
568 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
569 %                                                                             %
570 %                                                                             %
571 %                                                                             %
572 %   U n r e g i s t e r T G A I m a g e                                       %
573 %                                                                             %
574 %                                                                             %
575 %                                                                             %
576 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
577 %
578 %  UnregisterTGAImage() removes format registrations made by the
579 %  TGA module from the list of supported formats.
580 %
581 %  The format of the UnregisterTGAImage method is:
582 %
583 %      UnregisterTGAImage(void)
584 %
585 */
586 ModuleExport void UnregisterTGAImage(void)
587 {
588   (void) UnregisterMagickInfo("ICB");
589   (void) UnregisterMagickInfo("TGA");
590   (void) UnregisterMagickInfo("VDA");
591   (void) UnregisterMagickInfo("VST");
592 }
593 \f
594 /*
595 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
596 %                                                                             %
597 %                                                                             %
598 %                                                                             %
599 %   W r i t e T G A I m a g e                                                 %
600 %                                                                             %
601 %                                                                             %
602 %                                                                             %
603 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
604 %
605 %  WriteTGAImage() writes a image in the Truevision Targa rasterfile
606 %  format.
607 %
608 %  The format of the WriteTGAImage method is:
609 %
610 %      MagickBooleanType WriteTGAImage(const ImageInfo *image_info,
611 %        Image *image,ExceptionInfo *exception)
612 %
613 %  A description of each parameter follows.
614 %
615 %    o image_info: the image info.
616 %
617 %    o image:  The image.
618 %
619 */
620
621 static inline size_t MagickMin(const size_t x,const size_t y)
622 {
623   if (x < y)
624     return(x);
625   return(y);
626 }
627
628 static MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image,
629   ExceptionInfo *exception)
630 {
631 #define TargaColormap 1
632 #define TargaRGB 2
633 #define TargaMonochrome 3
634 #define TargaRLEColormap  9
635 #define TargaRLERGB  10
636 #define TargaRLEMonochrome  11
637
638   typedef struct _TargaInfo
639   {
640     unsigned char
641       id_length,
642       colormap_type,
643       image_type;
644
645     unsigned short
646       colormap_index,
647       colormap_length;
648
649     unsigned char
650       colormap_size;
651
652     unsigned short
653       x_origin,
654       y_origin,
655       width,
656       height;
657
658     unsigned char
659       bits_per_pixel,
660       attributes;
661   } TargaInfo;
662
663   const char
664     *value;
665
666   MagickBooleanType
667     status;
668
669   register const Quantum
670     *p;
671
672   register ssize_t
673     x;
674
675   register ssize_t
676     i;
677
678   register unsigned char
679     *q;
680
681   ssize_t
682     count,
683     y;
684
685   TargaInfo
686     targa_info;
687
688   unsigned char
689     *targa_pixels;
690
691   /*
692     Open output image file.
693   */
694   assert(image_info != (const ImageInfo *) NULL);
695   assert(image_info->signature == MagickSignature);
696   assert(image != (Image *) NULL);
697   assert(image->signature == MagickSignature);
698   if (image->debug != MagickFalse)
699     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
700   assert(exception != (ExceptionInfo *) NULL);
701   assert(exception->signature == MagickSignature);
702   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
703   if (status == MagickFalse)
704     return(status);
705   /*
706     Initialize TGA raster file header.
707   */
708   if ((image->columns > 65535L) || (image->rows > 65535L))
709     ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
710   if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
711     (void) TransformImageColorspace(image,sRGBColorspace,exception);
712   targa_info.id_length=0;
713   value=GetImageProperty(image,"comment",exception);
714   if (value != (const char *) NULL)
715     targa_info.id_length=(unsigned char) MagickMin(strlen(value),255);
716   targa_info.colormap_type=0;
717   targa_info.colormap_index=0;
718   targa_info.colormap_length=0;
719   targa_info.colormap_size=0;
720   targa_info.x_origin=0;
721   targa_info.y_origin=0;
722   targa_info.width=(unsigned short) image->columns;
723   targa_info.height=(unsigned short) image->rows;
724   targa_info.bits_per_pixel=8;
725   targa_info.attributes=0;
726   if ((image_info->type != TrueColorType) &&
727       (image_info->type != TrueColorMatteType) &&
728       (image_info->type != PaletteType) &&
729       (image->alpha_trait != BlendPixelTrait) &&
730       (IsImageGray(image,exception) != MagickFalse))
731     targa_info.image_type=TargaMonochrome;
732   else
733     if ((image->storage_class == DirectClass) || (image->colors > 256))
734       {
735         /*
736           Full color TGA raster.
737         */
738         targa_info.image_type=TargaRGB;
739         targa_info.bits_per_pixel=24;
740         if (image->alpha_trait == BlendPixelTrait)
741           {
742             targa_info.bits_per_pixel=32;
743             targa_info.attributes=8;  /* # of alpha bits */
744           }
745       }
746     else
747       {
748         /*
749           Colormapped TGA raster.
750         */
751         targa_info.image_type=TargaColormap;
752         targa_info.colormap_type=1;
753         targa_info.colormap_length=(unsigned short) image->colors;
754         targa_info.colormap_size=24;
755       }
756   /*
757     Write TGA header.
758   */
759   (void) WriteBlobByte(image,targa_info.id_length);
760   (void) WriteBlobByte(image,targa_info.colormap_type);
761   (void) WriteBlobByte(image,targa_info.image_type);
762   (void) WriteBlobLSBShort(image,targa_info.colormap_index);
763   (void) WriteBlobLSBShort(image,targa_info.colormap_length);
764   (void) WriteBlobByte(image,targa_info.colormap_size);
765   (void) WriteBlobLSBShort(image,targa_info.x_origin);
766   (void) WriteBlobLSBShort(image,targa_info.y_origin);
767   (void) WriteBlobLSBShort(image,targa_info.width);
768   (void) WriteBlobLSBShort(image,targa_info.height);
769   (void) WriteBlobByte(image,targa_info.bits_per_pixel);
770   (void) WriteBlobByte(image,targa_info.attributes);
771   if (targa_info.id_length != 0)
772     (void) WriteBlob(image,targa_info.id_length,(unsigned char *)
773       value);
774   if (targa_info.image_type == TargaColormap)
775     {
776       unsigned char
777         *targa_colormap;
778
779       /*
780         Dump colormap to file (blue, green, red byte order).
781       */
782       targa_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
783         targa_info.colormap_length,3UL*sizeof(*targa_colormap));
784       if (targa_colormap == (unsigned char *) NULL)
785         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
786       q=targa_colormap;
787       for (i=0; i < (ssize_t) image->colors; i++)
788       {
789         *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
790         *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
791         *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
792       }
793       (void) WriteBlob(image,(size_t) (3*targa_info.colormap_length),
794         targa_colormap);
795       targa_colormap=(unsigned char *) RelinquishMagickMemory(targa_colormap);
796     }
797   /*
798     Convert MIFF to TGA raster pixels.
799   */
800   count=(ssize_t) (targa_info.bits_per_pixel*targa_info.width)/8;
801   targa_pixels=(unsigned char *) AcquireQuantumMemory((size_t) count,
802     sizeof(*targa_pixels));
803   if (targa_pixels == (unsigned char *) NULL)
804     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
805   for (y=(ssize_t) (image->rows-1); y >= 0; y--)
806   {
807     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
808     if (p == (const Quantum *) NULL)
809       break;
810     q=targa_pixels;
811     for (x=0; x < (ssize_t) image->columns; x++)
812     {
813       if (targa_info.image_type == TargaColormap)
814         *q++=(unsigned char) GetPixelIndex(image,p);
815       else
816         if (targa_info.image_type == TargaMonochrome)
817           *q++=(unsigned char) ScaleQuantumToChar((ClampToQuantum(
818             GetPixelIntensity(image,p))));
819         else
820           {
821             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
822             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
823             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
824             if (image->alpha_trait == BlendPixelTrait)
825               *q++=(unsigned char) ScaleQuantumToChar(GetPixelAlpha(image,p));
826           }
827       p+=GetPixelChannels(image);
828     }
829     (void) WriteBlob(image,(size_t) (q-targa_pixels),targa_pixels);
830     if (image->previous == (Image *) NULL)
831       {
832         status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
833           image->rows);
834         if (status == MagickFalse)
835           break;
836       }
837   }
838   targa_pixels=(unsigned char *) RelinquishMagickMemory(targa_pixels);
839   (void) CloseBlob(image);
840   return(MagickTrue);
841 }