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