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