2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5 % M M AAA TTTTT L AAA BBBB %
6 % MM MM A A T L A A B B %
7 % M M M AAAAA T L AAAAA BBBB %
8 % M M A A T L A A B B %
9 % M M A A T LLLLL A A BBBB %
12 % Read MATLAB Image Format %
19 % Permission is hereby granted, free of charge, to any person obtaining a %
20 % copy of this software and associated documentation files ("ImageMagick"), %
21 % to deal in ImageMagick without restriction, including without limitation %
22 % the rights to use, copy, modify, merge, publish, distribute, sublicense, %
23 % and/or sell copies of ImageMagick, and to permit persons to whom the %
24 % ImageMagick is furnished to do so, subject to the following conditions: %
26 % The above copyright notice and this permission notice shall be included in %
27 % all copies or substantial portions of ImageMagick. %
29 % The software is provided "as is", without warranty of any kind, express or %
30 % implied, including but not limited to the warranties of merchantability, %
31 % fitness for a particular purpose and noninfringement. In no event shall %
32 % ImageMagick Studio be liable for any claim, damages or other liability, %
33 % whether in an action of contract, tort or otherwise, arising from, out of %
34 % or in connection with ImageMagick or the use or other dealings in %
37 % Except as contained in this notice, the name of the ImageMagick Studio %
38 % shall not be used in advertising or otherwise to promote the sale, use or %
39 % other dealings in ImageMagick without prior written authorization from the %
40 % ImageMagick Studio. %
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
50 #include "MagickCore/studio.h"
51 #include "MagickCore/attribute.h"
52 #include "MagickCore/blob.h"
53 #include "MagickCore/blob-private.h"
54 #include "MagickCore/cache.h"
55 #include "MagickCore/color-private.h"
56 #include "MagickCore/colormap.h"
57 #include "MagickCore/colorspace-private.h"
58 #include "MagickCore/exception.h"
59 #include "MagickCore/exception-private.h"
60 #include "MagickCore/image.h"
61 #include "MagickCore/image-private.h"
62 #include "MagickCore/list.h"
63 #include "MagickCore/magick.h"
64 #include "MagickCore/memory_.h"
65 #include "MagickCore/monitor.h"
66 #include "MagickCore/monitor-private.h"
67 #include "MagickCore/pixel-accessor.h"
68 #include "MagickCore/quantum-private.h"
69 #include "MagickCore/option.h"
70 #include "MagickCore/pixel.h"
71 #include "MagickCore/resource_.h"
72 #include "MagickCore/shear.h"
73 #include "MagickCore/static.h"
74 #include "MagickCore/string_.h"
75 #include "MagickCore/module.h"
76 #include "MagickCore/transform.h"
77 #include "MagickCore/utility-private.h"
78 #if defined(MAGICKCORE_ZLIB_DELEGATE)
85 static MagickBooleanType
86 WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);
89 /* Auto coloring method, sorry this creates some artefact inside data
90 MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
91 MinReal+j*0 = white MaxReal+j*0 = black
92 MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
98 unsigned short Version;
99 char EndianIndicator[2];
100 unsigned long DataType;
101 unsigned long ObjectSize;
102 unsigned long unknown1;
103 unsigned long unknown2;
105 unsigned short unknown5;
106 unsigned char StructureFlag;
107 unsigned char StructureClass;
108 unsigned long unknown3;
109 unsigned long unknown4;
110 unsigned long DimFlag;
114 unsigned short Flag1;
115 unsigned short NameFlag;
119 static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
120 static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
121 static const char *OsDesc=
134 miINT8 = 1, /* 8 bit signed */
135 miUINT8, /* 8 bit unsigned */
136 miINT16, /* 16 bit signed */
137 miUINT16, /* 16 bit unsigned */
138 miINT32, /* 32 bit signed */
139 miUINT32, /* 32 bit unsigned */
140 miSINGLE, /* IEEE 754 single precision float */
142 miDOUBLE, /* IEEE 754 double precision float */
145 miINT64, /* 64 bit signed */
146 miUINT64, /* 64 bit unsigned */
147 miMATRIX, /* MATLAB array */
148 miCOMPRESSED, /* Compressed Data */
149 miUTF8, /* Unicode UTF-8 Encoded Character Data */
150 miUTF16, /* Unicode UTF-16 Encoded Character Data */
151 miUTF32 /* Unicode UTF-32 Encoded Character Data */
156 mxCELL_CLASS=1, /* cell array */
157 mxSTRUCT_CLASS, /* structure */
158 mxOBJECT_CLASS, /* object */
159 mxCHAR_CLASS, /* character array */
160 mxSPARSE_CLASS, /* sparse array */
161 mxDOUBLE_CLASS, /* double precision array */
162 mxSINGLE_CLASS, /* single precision floating point */
163 mxINT8_CLASS, /* 8 bit signed integer */
164 mxUINT8_CLASS, /* 8 bit unsigned integer */
165 mxINT16_CLASS, /* 16 bit signed integer */
166 mxUINT16_CLASS, /* 16 bit unsigned integer */
167 mxINT32_CLASS, /* 32 bit signed integer */
168 mxUINT32_CLASS, /* 32 bit unsigned integer */
169 mxINT64_CLASS, /* 64 bit signed integer */
170 mxUINT64_CLASS, /* 64 bit unsigned integer */
171 mxFUNCTION_CLASS /* Function handle */
174 #define FLAG_COMPLEX 0x8
175 #define FLAG_GLOBAL 0x4
176 #define FLAG_LOGICAL 0x2
178 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
181 static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
196 exception=(&image->exception);
197 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
198 if (q == (Quantum *) NULL)
200 for (x = 0; x < (ssize_t) image->columns; x++)
204 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
205 if (f + GetPixelRed(image,q) > QuantumRange)
206 SetPixelRed(image,QuantumRange,q);
208 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
209 if ((int) f / 2.0 > GetPixelGreen(image,q))
211 SetPixelGreen(image,0,q);
212 SetPixelBlue(image,0,q);
216 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
217 SetPixelGreen(image,GetPixelBlue(image,q),q);
222 f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));
223 if (f+GetPixelBlue(image,q) > QuantumRange)
224 SetPixelBlue(image,QuantumRange,q);
226 SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);
227 if ((int) f / 2.0 > GetPixelGreen(image,q))
229 SetPixelRed(image,0,q);
230 SetPixelGreen(image,0,q);
234 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
235 SetPixelGreen(image,GetPixelRed(image,q),q);
239 q+=GetPixelChannels(image);
241 if (!SyncAuthenticPixels(image,exception))
247 static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
262 exception=(&image->exception);
263 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
264 if (q == (Quantum *) NULL)
266 for (x = 0; x < (ssize_t) image->columns; x++)
270 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
271 if (f+GetPixelRed(image,q) > QuantumRange)
272 SetPixelRed(image,QuantumRange,q);
274 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
275 if ((int) f / 2.0 > GetPixelGreen(image,q))
277 SetPixelGreen(image,0,q);
278 SetPixelBlue(image,0,q);
282 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
283 SetPixelGreen(image,GetPixelBlue(image,q),q);
288 f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));
289 if (f + GetPixelBlue(image,q) > QuantumRange)
290 SetPixelBlue(image,QuantumRange,q);
292 SetPixelBlue(image,GetPixelBlue(image,q)+
294 if ((int) f / 2.0 > GetPixelGreen(image,q))
296 SetPixelGreen(image,0,q);
297 SetPixelRed(image,0,q);
301 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
302 SetPixelGreen(image,GetPixelRed(image,q),q);
308 if (!SyncAuthenticPixels(image,exception))
314 /************** READERS ******************/
316 /* This function reads one block of floats*/
317 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
321 *data++ = ReadBlobFloat(image);
322 len -= sizeof(float);
325 (void) SeekBlob(image, len, SEEK_CUR);
328 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
332 *data++ = ReadBlobFloat(image);
333 len -= sizeof(float);
336 (void) SeekBlob(image, len, SEEK_CUR);
339 /* This function reads one block of doubles*/
340 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
344 *data++ = ReadBlobDouble(image);
345 len -= sizeof(double);
348 (void) SeekBlob(image, len, SEEK_CUR);
351 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
355 *data++ = ReadBlobDouble(image);
356 len -= sizeof(double);
359 (void) SeekBlob(image, len, SEEK_CUR);
362 /* Calculate minimum and maximum from a given block of data */
363 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
365 MagickOffsetType filepos;
367 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
368 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
372 if (endian_indicator == LSBEndian)
374 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
375 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
379 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
380 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
383 filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
384 for (i = 0; i < SizeY; i++)
386 if (CellType==miDOUBLE)
388 ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
389 dblrow = (double *)BImgBuff;
392 *Min = *Max = *dblrow;
394 for (x = 0; x < SizeX; x++)
403 if (CellType==miSINGLE)
405 ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
406 fltrow = (float *)BImgBuff;
409 *Min = *Max = *fltrow;
411 for (x = 0; x < (ssize_t) SizeX; x++)
421 (void) SeekBlob(image, filepos, SEEK_SET);
425 static void FixSignedValues(const Image *image,Quantum *q, int y)
429 /* Please note that negative values will overflow
430 Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
431 <-1;-128> + 127+1 = <0; 127> */
432 SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
433 SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
434 SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
440 /** Fix whole row of logical/binary data. It means pack it. */
441 static void FixLogical(unsigned char *Buff,int ldblk)
443 unsigned char mask=128;
444 unsigned char *BuffL = Buff;
445 unsigned char val = 0;
464 #if defined(MAGICKCORE_ZLIB_DELEGATE)
465 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
469 return((voidpf) AcquireQuantumMemory(items,size));
472 static void RelinquishZIPMemory(voidpf context,voidpf memory)
475 memory=RelinquishMagickMemory(memory);
479 #if defined(MAGICKCORE_ZLIB_DELEGATE)
480 /** This procedure decompreses an image block for a new MATLAB format. */
481 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
485 void *CacheBlock, *DecompressBlock;
493 if(clone_info==NULL) return NULL;
494 if(clone_info->file) /* Close file opened from previous transaction. */
496 fclose(clone_info->file);
497 clone_info->file = NULL;
498 (void) remove_utf8(clone_info->filename);
501 CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
502 if(CacheBlock==NULL) return NULL;
503 DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
504 if(DecompressBlock==NULL)
506 RelinquishMagickMemory(CacheBlock);
510 mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
513 RelinquishMagickMemory(CacheBlock);
514 RelinquishMagickMemory(DecompressBlock);
515 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
519 zip_info.zalloc=AcquireZIPMemory;
520 zip_info.zfree=RelinquishZIPMemory;
521 zip_info.opaque = (voidpf) NULL;
522 inflateInit(&zip_info);
523 /* zip_info.next_out = 8*4;*/
525 zip_info.avail_in = 0;
526 zip_info.total_out = 0;
527 while(Size>0 && !EOFBlob(orig))
529 magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
530 zip_info.next_in = (Bytef *) CacheBlock;
531 zip_info.avail_in = (uInt) magick_size;
533 while(zip_info.avail_in>0)
535 zip_info.avail_out = 4096;
536 zip_info.next_out = (Bytef *) DecompressBlock;
537 status = inflate(&zip_info,Z_NO_FLUSH);
538 extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
541 if(status == Z_STREAM_END) goto DblBreak;
548 (void)fclose(mat_file);
549 RelinquishMagickMemory(CacheBlock);
550 RelinquishMagickMemory(DecompressBlock);
552 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
553 if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;
554 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
555 if (status == MagickFalse)
557 DeleteImageFromList(&image2);
559 fclose(clone_info->file);
560 clone_info->file = NULL;
562 (void) remove_utf8(clone_info->filename);
571 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
575 % R e a d M A T L A B i m a g e %
579 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
581 % ReadMATImage() reads an MAT X image file and returns it. It
582 % allocates the memory necessary for the new Image structure and returns a
583 % pointer to the new image.
585 % The format of the ReadMATImage method is:
587 % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
589 % A description of each parameter follows:
591 % o image: Method ReadMATImage returns a pointer to the image after
592 % reading. A null image is returned if there is a memory shortage or if
593 % the image cannot be read.
595 % o image_info: Specifies a pointer to a ImageInfo structure.
597 % o exception: return any errors or warnings in this structure.
601 static inline size_t MagickMin(const size_t x,const size_t y)
608 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
610 Image *image, *image2=NULL,
615 MATHeader MATLAB_HDR;
618 QuantumInfo *quantum_info;
619 ImageInfo *clone_info;
622 unsigned char *BImgBuff = NULL;
623 double MinVal, MaxVal;
628 MagickOffsetType filepos=0x80;
632 unsigned int (*ReadBlobXXXLong)(Image *image);
633 unsigned short (*ReadBlobXXXShort)(Image *image);
634 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
635 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
638 assert(image_info != (const ImageInfo *) NULL);
639 assert(image_info->signature == MagickSignature);
640 assert(exception != (ExceptionInfo *) NULL);
641 assert(exception->signature == MagickSignature);
642 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
647 image = AcquireImage(image_info,exception);
649 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
650 if (status == MagickFalse)
652 image=DestroyImageList(image);
653 return((Image *) NULL);
658 clone_info=CloneImageInfo(image_info);
659 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
660 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
661 MATLAB_HDR.Version = ReadBlobLSBShort(image);
662 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
663 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
665 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
666 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
667 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
669 ReadBlobXXXLong = ReadBlobLSBLong;
670 ReadBlobXXXShort = ReadBlobLSBShort;
671 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
672 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
673 image->endian = LSBEndian;
675 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
677 ReadBlobXXXLong = ReadBlobMSBLong;
678 ReadBlobXXXShort = ReadBlobMSBShort;
679 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
680 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
681 image->endian = MSBEndian;
684 goto MATLAB_KO; /* unsupported endian */
686 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
687 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
689 filepos = TellBlob(image);
690 while(!EOFBlob(image)) /* object parser loop */
692 (void) SeekBlob(image,filepos,SEEK_SET);
693 /* printf("pos=%X\n",TellBlob(image)); */
695 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
696 if(EOFBlob(image)) break;
697 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
698 if(EOFBlob(image)) break;
699 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
702 #if defined(MAGICKCORE_ZLIB_DELEGATE)
703 if(MATLAB_HDR.DataType == miCOMPRESSED)
705 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
706 if(image2==NULL) continue;
707 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
711 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
713 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
714 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
716 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
717 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
718 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
720 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
722 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
723 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
724 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
725 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
726 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
729 switch(MATLAB_HDR.DimFlag)
731 case 8: z=1; break; /* 2D matrix*/
732 case 12: z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
733 Unknown6 = ReadBlobXXXLong(image2);
735 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
737 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
740 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
741 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
743 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
744 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
745 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
746 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
747 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
748 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
749 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
750 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
751 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
752 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
753 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
754 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
755 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
756 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
758 switch (MATLAB_HDR.NameFlag)
761 size = ReadBlobXXXLong(image2); /* Object name string size */
762 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
763 (void) SeekBlob(image2, size, SEEK_CUR);
769 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
775 CellType = ReadBlobXXXLong(image2); /* Additional object type */
777 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
778 "MATLAB_HDR.CellType: %.20g",(double) CellType);
780 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
782 /* Image is gray when no complex flag is set and 2D Matrix */
783 if ((MATLAB_HDR.DimFlag == 8) &&
784 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
785 image->type=GrayscaleType;
792 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
795 image->depth = 8; /* Byte type cell */
796 ldblk = (ssize_t) MATLAB_HDR.SizeX;
801 image->depth = 16; /* Word type cell */
802 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
807 image->depth = 32; /* Dword type cell */
808 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
813 image->depth = 64; /* Qword type cell */
814 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
818 image->depth = 32; /* double type cell */
819 (void) SetImageOption(clone_info,"quantum:format","floating-point");
820 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
821 { /* complex float type cell */
823 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
827 image->depth = 64; /* double type cell */
828 (void) SetImageOption(clone_info,"quantum:format","floating-point");
829 if (sizeof(double) != 8)
830 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
831 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
832 { /* complex double type cell */
834 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
837 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
840 image->columns = MATLAB_HDR.SizeX;
841 image->rows = MATLAB_HDR.SizeY;
842 quantum_info=AcquireQuantumInfo(clone_info,image);
843 if (quantum_info == (QuantumInfo *) NULL)
844 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
846 image->colors = one << image->depth;
847 if (image->columns == 0 || image->rows == 0)
850 /* ----- Create gray palette ----- */
852 if (CellType==miUINT8 && z!=3)
854 if(image->colors>256) image->colors = 256;
856 if (AcquireImageColormap(image, image->colors,exception) == MagickFalse)
858 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
862 If ping is true, then only set image size and colors without
863 reading any image data.
865 if (image_info->ping)
867 size_t temp = image->columns;
868 image->columns = image->rows;
870 goto done_reading; /* !!!!!! BAD !!!! */
873 /* ----- Load raster data ----- */
874 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
875 if (BImgBuff == NULL)
880 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
882 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
885 /* Main loop for reading all scanlines */
886 if(z==1) z=0; /* read grey scanlines */
887 /* else read color scanlines */
890 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
892 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
893 if (q == (Quantum *)NULL)
895 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
896 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
897 goto done_reading; /* Skip image rotation, when cannot set image pixels */
899 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
901 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
902 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
905 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
907 FixLogical((unsigned char *)BImgBuff,ldblk);
908 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
910 ImportQuantumPixelsFailed:
911 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
912 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
918 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
919 goto ImportQuantumPixelsFailed;
922 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
923 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
924 FixSignedValues(image,q,MATLAB_HDR.SizeX);
927 if (!SyncAuthenticPixels(image,exception))
929 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
930 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
938 /* Read complex part of numbers here */
939 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
940 { /* Find Min and Max Values for complex parts of floats */
941 CellType = ReadBlobXXXLong(image2); /* Additional object type */
942 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
944 if (CellType==miDOUBLE || CellType==miSINGLE)
946 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
949 if (CellType==miDOUBLE)
950 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
952 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
953 InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
956 if (CellType==miSINGLE)
957 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
959 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
960 InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
964 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
965 if ((MATLAB_HDR.DimFlag == 8) &&
966 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
967 image->type=GrayscaleType;
968 if (image->depth == 1)
969 image->type=BilevelType;
972 image2 = NULL; /* Remove shadow copy to an image before rotation. */
975 rotated_image = RotateImage(image, 90.0, exception);
976 if (rotated_image != (Image *) NULL)
978 /* Remove page offsets added by RotateImage */
979 rotated_image->page.x=0;
980 rotated_image->page.y=0;
982 blob = rotated_image->blob;
983 rotated_image->blob = image->blob;
984 rotated_image->colors = image->colors;
986 AppendImageToList(&image,rotated_image);
987 DeleteImageFromList(&image);
995 DeleteImageFromList(&image2);
1000 fclose(clone_info->file);
1001 clone_info->file = NULL;
1002 (void) remove_utf8(clone_info->filename);
1007 /* Allocate next image structure. */
1008 AcquireNextImage(image_info,image,exception);
1009 if (image->next == (Image *) NULL) break;
1010 image=SyncNextImageInList(image);
1011 image->columns=image->rows=0;
1014 /* row scan buffer is no longer needed */
1015 RelinquishMagickMemory(BImgBuff);
1018 clone_info=DestroyImageInfo(clone_info);
1020 RelinquishMagickMemory(BImgBuff);
1029 Rewind list, removing any empty images while rewinding.
1033 while (p != (Image *)NULL)
1036 if ((p->rows == 0) || (p->columns == 0)) {
1038 DeleteImageFromList(&tmp);
1048 for (p=image; p != (Image *) NULL; p=p->next)
1052 if(clone_info != NULL) /* cleanup garbage file from compression */
1054 if(clone_info->file)
1056 fclose(clone_info->file);
1057 clone_info->file = NULL;
1058 (void) remove_utf8(clone_info->filename);
1060 DestroyImageInfo(clone_info);
1063 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1065 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1070 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1074 % R e g i s t e r M A T I m a g e %
1078 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1080 % Method RegisterMATImage adds attributes for the MAT image format to
1081 % the list of supported formats. The attributes include the image format
1082 % tag, a method to read and/or write the format, whether the format
1083 % supports the saving of more than one frame to the same file or blob,
1084 % whether the format supports native in-memory I/O, and a brief
1085 % description of the format.
1087 % The format of the RegisterMATImage method is:
1089 % size_t RegisterMATImage(void)
1092 ModuleExport size_t RegisterMATImage(void)
1097 entry=SetMagickInfo("MAT");
1098 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1099 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1100 entry->blob_support=MagickFalse;
1101 entry->seekable_stream=MagickTrue;
1102 entry->description=AcquireString("MATLAB level 5 image format");
1103 entry->module=AcquireString("MAT");
1104 (void) RegisterMagickInfo(entry);
1105 return(MagickImageCoderSignature);
1109 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1113 % U n r e g i s t e r M A T I m a g e %
1117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1119 % Method UnregisterMATImage removes format registrations made by the
1120 % MAT module from the list of supported formats.
1122 % The format of the UnregisterMATImage method is:
1124 % UnregisterMATImage(void)
1127 ModuleExport void UnregisterMATImage(void)
1129 (void) UnregisterMagickInfo("MAT");
1133 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1137 % W r i t e M A T L A B I m a g e %
1141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1143 % Function WriteMATImage writes an Matlab matrix to a file.
1145 % The format of the WriteMATImage method is:
1147 % MagickBooleanType WriteMATImage(const ImageInfo *image_info,
1148 % Image *image,ExceptionInfo *exception)
1150 % A description of each parameter follows.
1152 % o image_info: Specifies a pointer to a ImageInfo structure.
1154 % o image: A pointer to an Image structure.
1156 % o exception: return any errors or warnings in this structure.
1159 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
1160 ExceptionInfo *exception)
1164 register const Quantum *p;
1166 unsigned int status;
1170 char MATLAB_HDR[0x80];
1171 time_t current_time;
1172 struct tm local_time;
1173 unsigned char *pixels;
1183 Open output image file.
1185 assert(image_info != (const ImageInfo *) NULL);
1186 assert(image_info->signature == MagickSignature);
1187 assert(image != (Image *) NULL);
1188 assert(image->signature == MagickSignature);
1189 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1191 assert(exception != (ExceptionInfo *) NULL);
1192 assert(exception->signature == MagickSignature);
1193 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1194 if (status == MagickFalse)
1195 return(MagickFalse);
1198 current_time=time((time_t *) NULL);
1199 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1200 (void) localtime_r(¤t_time,&local_time);
1202 (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
1204 (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1205 FormatLocaleString(MATLAB_HDR,MaxTextExtent,"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1206 OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1207 local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1208 local_time.tm_sec,local_time.tm_year+1900);
1211 MATLAB_HDR[0x7E]='I';
1212 MATLAB_HDR[0x7F]='M';
1213 (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1217 if (IsRGBColorspace(image->colorspace) == MagickFalse)
1218 (void) TransformImageColorspace(image,RGBColorspace);
1220 is_gray = IsImageGray(image,exception);
1221 z = is_gray ? 0 : 3;
1226 DataSize = image->rows /*Y*/ * image->columns /*X*/;
1227 if(!is_gray) DataSize *= 3 /*Z*/;
1228 padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1230 (void) WriteBlobLSBLong(image, miMATRIX);
1231 (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
1232 (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1233 (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1234 (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
1235 (void) WriteBlobLSBLong(image, 0);
1236 (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1237 (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
1238 (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
1239 (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
1242 (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
1243 (void) WriteBlobLSBLong(image, 0);
1245 (void) WriteBlobLSBShort(image, 1); /* 0xB0 */
1246 (void) WriteBlobLSBShort(image, 1); /* 0xB2 */
1247 (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1248 (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
1249 (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
1254 quantum_info=AcquireQuantumInfo(image_info,image);
1255 if (quantum_info == (QuantumInfo *) NULL)
1256 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1257 pixels=GetQuantumPixels(quantum_info);
1260 for (y=0; y < (ssize_t)image->columns; y++)
1262 p=GetVirtualPixels(image,y,0,1,image->rows,exception);
1263 if (p == (const Quantum *) NULL)
1265 (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1266 z2qtype[z],pixels,exception);
1267 (void) WriteBlob(image,image->rows,pixels);
1269 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1272 while(padding-->0) (void) WriteBlobByte(image,0);
1273 quantum_info=DestroyQuantumInfo(quantum_info);
1274 if (GetNextImageInList(image) == (Image *) NULL)
1276 image=SyncNextImageInList(image);
1277 status=SetImageProgress(image,SaveImagesTag,scene++,
1278 GetImageListLength(image));
1279 if (status == MagickFalse)
1281 } while (image_info->adjoin != MagickFalse);
1282 (void) CloseBlob(image);