]> granicus.if.org Git - imagemagick/blob - coders/xbm.c
...
[imagemagick] / coders / xbm.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            X   X  BBBB   M   M                              %
7 %                             X X   B   B  MM MM                              %
8 %                              X    BBBB   M M M                              %
9 %                             X X   B   B  M   M                              %
10 %                            X   X  BBBB   M   M                              %
11 %                                                                             %
12 %                                                                             %
13 %                  Read/Write X Windows System Bitmap 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://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/colorspace.h"
50 #include "MagickCore/colorspace-private.h"
51 #include "MagickCore/exception.h"
52 #include "MagickCore/exception-private.h"
53 #include "MagickCore/image.h"
54 #include "MagickCore/image-private.h"
55 #include "MagickCore/list.h"
56 #include "MagickCore/magick.h"
57 #include "MagickCore/memory_.h"
58 #include "MagickCore/monitor.h"
59 #include "MagickCore/monitor-private.h"
60 #include "MagickCore/pixel-accessor.h"
61 #include "MagickCore/quantum-private.h"
62 #include "MagickCore/static.h"
63 #include "MagickCore/string_.h"
64 #include "MagickCore/module.h"
65 #include "MagickCore/utility.h"
66 \f
67 /*
68   Forward declarations.
69 */
70 static MagickBooleanType
71   WriteXBMImage(const ImageInfo *,Image *,ExceptionInfo *);
72 \f
73 /*
74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
75 %                                                                             %
76 %                                                                             %
77 %                                                                             %
78 %   I s X B M                                                                 %
79 %                                                                             %
80 %                                                                             %
81 %                                                                             %
82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83 %
84 %  IsXBM() returns MagickTrue if the image format type, identified by the
85 %  magick string, is XBM.
86 %
87 %  The format of the IsXBM method is:
88 %
89 %      MagickBooleanType IsXBM(const unsigned char *magick,const size_t length)
90 %
91 %  A description of each parameter follows:
92 %
93 %    o magick: compare image format pattern against these bytes.
94 %
95 %    o length: Specifies the length of the magick string.
96 %
97 */
98 static MagickBooleanType IsXBM(const unsigned char *magick,const size_t length)
99 {
100   if (length < 7)
101     return(MagickFalse);
102   if (memcmp(magick,"#define",7) == 0)
103     return(MagickTrue);
104   return(MagickFalse);
105 }
106 \f
107 /*
108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109 %                                                                             %
110 %                                                                             %
111 %                                                                             %
112 %   R e a d X B M I m a g e                                                   %
113 %                                                                             %
114 %                                                                             %
115 %                                                                             %
116 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
117 %
118 %  ReadXBMImage() reads an X11 bitmap image file and returns it.  It
119 %  allocates the memory necessary for the new Image structure and returns a
120 %  pointer to the new image.
121 %
122 %  The format of the ReadXBMImage method is:
123 %
124 %      Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception)
125 %
126 %  A description of each parameter follows:
127 %
128 %    o image_info: the image info.
129 %
130 %    o exception: return any errors or warnings in this structure.
131 %
132 */
133
134 static int XBMInteger(Image *image,short int *hex_digits)
135 {
136   int
137     c;
138
139   unsigned int
140     value;
141
142   /*
143     Skip any leading whitespace.
144   */
145   do
146   {
147     c=ReadBlobByte(image);
148     if (c == EOF)
149       return(-1);
150   } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
151   /*
152     Evaluate number.
153   */
154   value=0;
155   do
156   {
157     if (value <= (unsigned int) (INT_MAX/16))
158       {
159         value*=16;
160         c&=0xff;
161         if (value <= (unsigned int) (INT_MAX-hex_digits[c]))
162           value+=hex_digits[c];
163       }
164     c=ReadBlobByte(image);
165     if (c == EOF)
166       return(-1);
167   } while (hex_digits[c] >= 0);
168   return((int) value);
169 }
170
171 static Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception)
172 {
173   char
174     buffer[MagickPathExtent],
175     name[MagickPathExtent];
176
177   Image
178     *image;
179
180   int
181     c;
182
183   long
184     height,
185     width;
186
187   MagickBooleanType
188     status;
189
190   register ssize_t
191     i,
192     x;
193
194   register Quantum
195     *q;
196
197   register unsigned char
198     *p;
199
200   short int
201     hex_digits[256];
202
203   ssize_t
204     y;
205
206   unsigned char
207     *data;
208
209   unsigned int
210     bit,
211     byte,
212     bytes_per_line,
213     length,
214     padding,
215     version;
216
217   /*
218     Open image file.
219   */
220   assert(image_info != (const ImageInfo *) NULL);
221   assert(image_info->signature == MagickCoreSignature);
222   if (image_info->debug != MagickFalse)
223     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
224       image_info->filename);
225   assert(exception != (ExceptionInfo *) NULL);
226   assert(exception->signature == MagickCoreSignature);
227   image=AcquireImage(image_info,exception);
228   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
229   if (status == MagickFalse)
230     {
231       image=DestroyImageList(image);
232       return((Image *) NULL);
233     }
234   /*
235     Read X bitmap header.
236   */
237   width=0;
238   height=0;
239   *name='\0';
240   while (ReadBlobString(image,buffer) != (char *) NULL)
241     if (sscanf(buffer,"#define %1024s %ld",name,&width) == 2)
242       if ((strlen(name) >= 6) &&
243           (LocaleCompare(name+strlen(name)-6,"_width") == 0))
244         break;
245   while (ReadBlobString(image,buffer) != (char *) NULL)
246     if (sscanf(buffer,"#define %1024s %ld",name,&height) == 2)
247       if ((strlen(name) >= 7) &&
248           (LocaleCompare(name+strlen(name)-7,"_height") == 0))
249         break;
250   if ((width <= 0) || (height <= 0) || (EOFBlob(image) != MagickFalse))
251     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
252   image->columns=(size_t) width;
253   image->rows=(size_t) height;
254   image->depth=8;
255   image->storage_class=PseudoClass;
256   image->colors=2;
257   /*
258     Scan until hex digits.
259   */
260   version=11;
261   while (ReadBlobString(image,buffer) != (char *) NULL)
262   {
263     if (sscanf(buffer,"static short %1024s = {",name) == 1)
264       version=10;
265     else
266       if (sscanf(buffer,"static unsigned char %1024s = {",name) == 1)
267         version=11;
268       else
269         if (sscanf(buffer,"static char %1024s = {",name) == 1)
270           version=11;
271         else
272           continue;
273     p=(unsigned char *) strrchr(name,'_');
274     if (p == (unsigned char *) NULL)
275       p=(unsigned char *) name;
276     else
277       p++;
278     if (LocaleCompare("bits[]",(char *) p) == 0)
279       break;
280   }
281   /*
282     Initialize image structure.
283   */
284   if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
285     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
286   /*
287     Initialize colormap.
288   */
289   image->colormap[0].red=(MagickRealType) QuantumRange;
290   image->colormap[0].green=(MagickRealType) QuantumRange;
291   image->colormap[0].blue=(MagickRealType) QuantumRange;
292   image->colormap[1].red=0.0;
293   image->colormap[1].green=0.0;
294   image->colormap[1].blue=0.0;
295   if (image_info->ping != MagickFalse)
296     {
297       (void) CloseBlob(image);
298       return(GetFirstImageInList(image));
299     }
300   status=SetImageExtent(image,image->columns,image->rows,exception);
301   if (status == MagickFalse)
302     return(DestroyImageList(image));
303   /*
304     Initialize hex values.
305   */
306   for (i=0; i < (ssize_t) (sizeof(hex_digits)/sizeof(*hex_digits)); i++)
307     hex_digits[i]=(-1);
308   hex_digits[(int) '0']=0;
309   hex_digits[(int) '1']=1;
310   hex_digits[(int) '2']=2;
311   hex_digits[(int) '3']=3;
312   hex_digits[(int) '4']=4;
313   hex_digits[(int) '5']=5;
314   hex_digits[(int) '6']=6;
315   hex_digits[(int) '7']=7;
316   hex_digits[(int) '8']=8;
317   hex_digits[(int) '9']=9;
318   hex_digits[(int) 'A']=10;
319   hex_digits[(int) 'B']=11;
320   hex_digits[(int) 'C']=12;
321   hex_digits[(int) 'D']=13;
322   hex_digits[(int) 'E']=14;
323   hex_digits[(int) 'F']=15;
324   hex_digits[(int) 'a']=10;
325   hex_digits[(int) 'b']=11;
326   hex_digits[(int) 'c']=12;
327   hex_digits[(int) 'd']=13;
328   hex_digits[(int) 'e']=14;
329   hex_digits[(int) 'f']=15;
330   hex_digits[(int) 'x']=0;
331   hex_digits[(int) ' ']=(-1);
332   hex_digits[(int) ',']=(-1);
333   hex_digits[(int) '}']=(-1);
334   hex_digits[(int) '\n']=(-1);
335   hex_digits[(int) '\t']=(-1);
336   /*
337     Read hex image data.
338   */
339   padding=0;
340   if (((image->columns % 16) != 0) && ((image->columns % 16) < 9) &&
341       (version == 10))
342     padding=1;
343   bytes_per_line=(unsigned int) (image->columns+7)/8+padding;
344   length=(unsigned int) image->rows;
345   data=(unsigned char *) AcquireQuantumMemory(length,bytes_per_line*
346     sizeof(*data));
347   if (data == (unsigned char *) NULL)
348     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
349   p=data;
350   if (version == 10)
351     for (i=0; i < (ssize_t) (bytes_per_line*image->rows); (i+=2))
352     {
353       c=XBMInteger(image,hex_digits);
354       if (c < 0)
355         {
356           data=(unsigned char *) RelinquishMagickMemory(data);
357           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
358         }
359       *p++=(unsigned char) c;
360       if ((padding == 0) || (((i+2) % bytes_per_line) != 0))
361         *p++=(unsigned char) (c >> 8);
362     }
363   else
364     for (i=0; i < (ssize_t) (bytes_per_line*image->rows); i++)
365     {
366       c=XBMInteger(image,hex_digits);
367       if (c < 0)
368         {
369           data=(unsigned char *) RelinquishMagickMemory(data);
370           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
371         }
372       *p++=(unsigned char) c;
373     }
374   if (EOFBlob(image) != MagickFalse)
375     {
376       data=(unsigned char *) RelinquishMagickMemory(data);
377       ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
378     }
379   /*
380     Convert X bitmap image to pixel packets.
381   */
382   p=data;
383   for (y=0; y < (ssize_t) image->rows; y++)
384   {
385     q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
386     if (q == (Quantum *) NULL)
387       break;
388     bit=0;
389     byte=0;
390     for (x=0; x < (ssize_t) image->columns; x++)
391     {
392       if (bit == 0)
393         byte=(unsigned int) (*p++);
394       SetPixelIndex(image,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00),q);
395       bit++;
396       byte>>=1;
397       if (bit == 8)
398         bit=0;
399       q+=GetPixelChannels(image);
400     }
401     if (SyncAuthenticPixels(image,exception) == MagickFalse)
402       break;
403     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
404       image->rows);
405     if (status == MagickFalse)
406       break;
407   }
408   data=(unsigned char *) RelinquishMagickMemory(data);
409   (void) SyncImage(image,exception);
410   (void) CloseBlob(image);
411   return(GetFirstImageInList(image));
412 }
413 \f
414 /*
415 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
416 %                                                                             %
417 %                                                                             %
418 %                                                                             %
419 %   R e g i s t e r X B M I m a g e                                           %
420 %                                                                             %
421 %                                                                             %
422 %                                                                             %
423 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
424 %
425 %  RegisterXBMImage() adds attributes for the XBM image format to
426 %  the list of supported formats.  The attributes include the image format
427 %  tag, a method to read and/or write the format, whether the format
428 %  supports the saving of more than one frame to the same file or blob,
429 %  whether the format supports native in-memory I/O, and a brief
430 %  description of the format.
431 %
432 %  The format of the RegisterXBMImage method is:
433 %
434 %      size_t RegisterXBMImage(void)
435 %
436 */
437 ModuleExport size_t RegisterXBMImage(void)
438 {
439   MagickInfo
440     *entry;
441
442   entry=AcquireMagickInfo("XBM","XBM",
443     "X Windows system bitmap (black and white)");
444   entry->decoder=(DecodeImageHandler *) ReadXBMImage;
445   entry->encoder=(EncodeImageHandler *) WriteXBMImage;
446   entry->magick=(IsImageFormatHandler *) IsXBM;
447   entry->flags^=CoderAdjoinFlag;
448   (void) RegisterMagickInfo(entry);
449   return(MagickImageCoderSignature);
450 }
451 \f
452 /*
453 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
454 %                                                                             %
455 %                                                                             %
456 %                                                                             %
457 %   U n r e g i s t e r X B M I m a g e                                       %
458 %                                                                             %
459 %                                                                             %
460 %                                                                             %
461 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
462 %
463 %  UnregisterXBMImage() removes format registrations made by the
464 %  XBM module from the list of supported formats.
465 %
466 %  The format of the UnregisterXBMImage method is:
467 %
468 %      UnregisterXBMImage(void)
469 %
470 */
471 ModuleExport void UnregisterXBMImage(void)
472 {
473   (void) UnregisterMagickInfo("XBM");
474 }
475 \f
476 /*
477 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
478 %                                                                             %
479 %                                                                             %
480 %                                                                             %
481 %   W r i t e X B M I m a g e                                                 %
482 %                                                                             %
483 %                                                                             %
484 %                                                                             %
485 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
486 %
487 %  WriteXBMImage() writes an image to a file in the X bitmap format.
488 %
489 %  The format of the WriteXBMImage method is:
490 %
491 %      MagickBooleanType WriteXBMImage(const ImageInfo *image_info,
492 %        Image *image,ExceptionInfo *exception)
493 %
494 %  A description of each parameter follows.
495 %
496 %    o image_info: the image info.
497 %
498 %    o image:  The image.
499 %
500 %    o exception: return any errors or warnings in this structure.
501 %
502 */
503 static MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image,
504   ExceptionInfo *exception)
505 {
506   char
507     basename[MagickPathExtent],
508     buffer[MagickPathExtent];
509
510   MagickBooleanType
511     status;
512
513   register const Quantum
514     *p;
515
516   register ssize_t
517     x;
518
519   size_t
520     bit,
521     byte;
522
523   ssize_t
524     count,
525     y;
526
527   /*
528     Open output image file.
529   */
530   assert(image_info != (const ImageInfo *) NULL);
531   assert(image_info->signature == MagickCoreSignature);
532   assert(image != (Image *) NULL);
533   assert(image->signature == MagickCoreSignature);
534   if (image->debug != MagickFalse)
535     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
536   assert(exception != (ExceptionInfo *) NULL);
537   assert(exception->signature == MagickCoreSignature);
538   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
539   if (status == MagickFalse)
540     return(status);
541   (void) TransformImageColorspace(image,sRGBColorspace,exception);
542   /*
543     Write X bitmap header.
544   */
545   GetPathComponent(image->filename,BasePath,basename);
546   (void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_width %.20g\n",
547     basename,(double) image->columns);
548   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
549   (void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_height %.20g\n",
550     basename,(double) image->rows);
551   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
552   (void) FormatLocaleString(buffer,MagickPathExtent,
553     "static char %s_bits[] = {\n",basename);
554   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
555   (void) CopyMagickString(buffer," ",MagickPathExtent);
556   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
557   /*
558     Convert MIFF to X bitmap pixels.
559   */
560   (void) SetImageType(image,BilevelType,exception);
561   bit=0;
562   byte=0;
563   count=0;
564   x=0;
565   y=0;
566   (void) CopyMagickString(buffer," ",MagickPathExtent);
567   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
568   for (y=0; y < (ssize_t) image->rows; y++)
569   {
570     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
571     if (p == (const Quantum *) NULL)
572       break;
573     for (x=0; x < (ssize_t) image->columns; x++)
574     {
575       byte>>=1;
576       if (GetPixelLuma(image,p) < (QuantumRange/2))
577         byte|=0x80;
578       bit++;
579       if (bit == 8)
580         {
581           /*
582             Write a bitmap byte to the image file.
583           */
584           (void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ",
585             (unsigned int) (byte & 0xff));
586           (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
587           count++;
588           if (count == 12)
589             {
590               (void) CopyMagickString(buffer,"\n  ",MagickPathExtent);
591               (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
592               count=0;
593             };
594           bit=0;
595           byte=0;
596         }
597         p+=GetPixelChannels(image);
598       }
599     if (bit != 0)
600       {
601         /*
602           Write a bitmap byte to the image file.
603         */
604         byte>>=(8-bit);
605         (void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ",
606           (unsigned int) (byte & 0xff));
607         (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
608         count++;
609         if (count == 12)
610           {
611             (void) CopyMagickString(buffer,"\n  ",MagickPathExtent);
612             (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
613             count=0;
614           };
615         bit=0;
616         byte=0;
617       };
618     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
619       image->rows);
620     if (status == MagickFalse)
621       break;
622   }
623   (void) CopyMagickString(buffer,"};\n",MagickPathExtent);
624   (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
625   (void) CloseBlob(image);
626   return(MagickTrue);
627 }