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 #if defined(MAGICKCORE_ZLIB_DELEGATE)
84 static MagickBooleanType
85 WriteMATImage(const ImageInfo *,Image *);
88 /* Auto coloring method, sorry this creates some artefact inside data
89 MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
90 MinReal+j*0 = white MaxReal+j*0 = black
91 MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
97 unsigned short Version;
98 char EndianIndicator[2];
99 unsigned long DataType;
100 unsigned long ObjectSize;
101 unsigned long unknown1;
102 unsigned long unknown2;
104 unsigned short unknown5;
105 unsigned char StructureFlag;
106 unsigned char StructureClass;
107 unsigned long unknown3;
108 unsigned long unknown4;
109 unsigned long DimFlag;
113 unsigned short Flag1;
114 unsigned short NameFlag;
118 static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
119 static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
120 static const char *OsDesc=
133 miINT8 = 1, /* 8 bit signed */
134 miUINT8, /* 8 bit unsigned */
135 miINT16, /* 16 bit signed */
136 miUINT16, /* 16 bit unsigned */
137 miINT32, /* 32 bit signed */
138 miUINT32, /* 32 bit unsigned */
139 miSINGLE, /* IEEE 754 single precision float */
141 miDOUBLE, /* IEEE 754 double precision float */
144 miINT64, /* 64 bit signed */
145 miUINT64, /* 64 bit unsigned */
146 miMATRIX, /* MATLAB array */
147 miCOMPRESSED, /* Compressed Data */
148 miUTF8, /* Unicode UTF-8 Encoded Character Data */
149 miUTF16, /* Unicode UTF-16 Encoded Character Data */
150 miUTF32 /* Unicode UTF-32 Encoded Character Data */
155 mxCELL_CLASS=1, /* cell array */
156 mxSTRUCT_CLASS, /* structure */
157 mxOBJECT_CLASS, /* object */
158 mxCHAR_CLASS, /* character array */
159 mxSPARSE_CLASS, /* sparse array */
160 mxDOUBLE_CLASS, /* double precision array */
161 mxSINGLE_CLASS, /* single precision floating point */
162 mxINT8_CLASS, /* 8 bit signed integer */
163 mxUINT8_CLASS, /* 8 bit unsigned integer */
164 mxINT16_CLASS, /* 16 bit signed integer */
165 mxUINT16_CLASS, /* 16 bit unsigned integer */
166 mxINT32_CLASS, /* 32 bit signed integer */
167 mxUINT32_CLASS, /* 32 bit unsigned integer */
168 mxINT64_CLASS, /* 64 bit signed integer */
169 mxUINT64_CLASS, /* 64 bit unsigned integer */
170 mxFUNCTION_CLASS /* Function handle */
173 #define FLAG_COMPLEX 0x8
174 #define FLAG_GLOBAL 0x4
175 #define FLAG_LOGICAL 0x2
177 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
180 static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
195 exception=(&image->exception);
196 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
197 if (q == (const Quantum *) NULL)
199 for (x = 0; x < (ssize_t) image->columns; x++)
203 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
204 if (f + GetPixelRed(image,q) > QuantumRange)
205 SetPixelRed(image,QuantumRange,q);
207 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
208 if ((int) f / 2.0 > GetPixelGreen(image,q))
210 SetPixelGreen(image,0,q);
211 SetPixelBlue(image,0,q);
215 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
216 SetPixelGreen(image,GetPixelBlue(image,q),q);
221 f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));
222 if (f+GetPixelBlue(image,q) > QuantumRange)
223 SetPixelBlue(image,QuantumRange,q);
225 SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);
226 if ((int) f / 2.0 > GetPixelGreen(image,q))
228 SetPixelRed(image,0,q);
229 SetPixelGreen(image,0,q);
233 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
234 SetPixelGreen(image,GetPixelRed(image,q),q);
238 q+=GetPixelChannels(image);
240 if (!SyncAuthenticPixels(image,exception))
246 static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
261 exception=(&image->exception);
262 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
263 if (q == (const Quantum *) NULL)
265 for (x = 0; x < (ssize_t) image->columns; x++)
269 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
270 if (f+GetPixelRed(image,q) > QuantumRange)
271 SetPixelRed(image,QuantumRange,q);
273 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
274 if ((int) f / 2.0 > GetPixelGreen(image,q))
276 SetPixelGreen(image,0,q);
277 SetPixelBlue(image,0,q);
281 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
282 SetPixelGreen(image,GetPixelBlue(image,q),q);
287 f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));
288 if (f + GetPixelBlue(image,q) > QuantumRange)
289 SetPixelBlue(image,QuantumRange,q);
291 SetPixelBlue(image,GetPixelBlue(image,q)+
293 if ((int) f / 2.0 > GetPixelGreen(image,q))
295 SetPixelGreen(image,0,q);
296 SetPixelRed(image,0,q);
300 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
301 SetPixelGreen(image,GetPixelRed(image,q),q);
307 if (!SyncAuthenticPixels(image,exception))
313 /************** READERS ******************/
315 /* This function reads one block of floats*/
316 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
320 *data++ = ReadBlobFloat(image);
321 len -= sizeof(float);
324 (void) SeekBlob(image, len, SEEK_CUR);
327 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
331 *data++ = ReadBlobFloat(image);
332 len -= sizeof(float);
335 (void) SeekBlob(image, len, SEEK_CUR);
338 /* This function reads one block of doubles*/
339 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
343 *data++ = ReadBlobDouble(image);
344 len -= sizeof(double);
347 (void) SeekBlob(image, len, SEEK_CUR);
350 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
354 *data++ = ReadBlobDouble(image);
355 len -= sizeof(double);
358 (void) SeekBlob(image, len, SEEK_CUR);
361 /* Calculate minimum and maximum from a given block of data */
362 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
364 MagickOffsetType filepos;
366 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
367 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
371 if (endian_indicator == LSBEndian)
373 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
374 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
378 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
379 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
382 filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
383 for (i = 0; i < SizeY; i++)
385 if (CellType==miDOUBLE)
387 ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
388 dblrow = (double *)BImgBuff;
391 *Min = *Max = *dblrow;
393 for (x = 0; x < SizeX; x++)
402 if (CellType==miSINGLE)
404 ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
405 fltrow = (float *)BImgBuff;
408 *Min = *Max = *fltrow;
410 for (x = 0; x < (ssize_t) SizeX; x++)
420 (void) SeekBlob(image, filepos, SEEK_SET);
424 static void FixSignedValues(const Image *image,Quantum *q, int y)
428 /* Please note that negative values will overflow
429 Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
430 <-1;-128> + 127+1 = <0; 127> */
431 SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
432 SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
433 SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
439 /** Fix whole row of logical/binary data. It means pack it. */
440 static void FixLogical(unsigned char *Buff,int ldblk)
442 unsigned char mask=128;
443 unsigned char *BuffL = Buff;
444 unsigned char val = 0;
463 #if defined(MAGICKCORE_ZLIB_DELEGATE)
464 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
468 return((voidpf) AcquireQuantumMemory(items,size));
471 static void RelinquishZIPMemory(voidpf context,voidpf memory)
474 memory=RelinquishMagickMemory(memory);
478 #if defined(MAGICKCORE_ZLIB_DELEGATE)
479 /** This procedure decompreses an image block for a new MATLAB format. */
480 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
484 void *CacheBlock, *DecompressBlock;
492 if(clone_info==NULL) return NULL;
493 if(clone_info->file) /* Close file opened from previous transaction. */
495 fclose(clone_info->file);
496 clone_info->file = NULL;
497 (void) unlink(clone_info->filename);
500 CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
501 if(CacheBlock==NULL) return NULL;
502 DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
503 if(DecompressBlock==NULL)
505 RelinquishMagickMemory(CacheBlock);
509 mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
512 RelinquishMagickMemory(CacheBlock);
513 RelinquishMagickMemory(DecompressBlock);
514 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
518 zip_info.zalloc=AcquireZIPMemory;
519 zip_info.zfree=RelinquishZIPMemory;
520 zip_info.opaque = (voidpf) NULL;
521 inflateInit(&zip_info);
522 /* zip_info.next_out = 8*4;*/
524 zip_info.avail_in = 0;
525 zip_info.total_out = 0;
526 while(Size>0 && !EOFBlob(orig))
528 magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
529 zip_info.next_in = (Bytef *) CacheBlock;
530 zip_info.avail_in = (uInt) magick_size;
532 while(zip_info.avail_in>0)
534 zip_info.avail_out = 4096;
535 zip_info.next_out = (Bytef *) DecompressBlock;
536 status = inflate(&zip_info,Z_NO_FLUSH);
537 extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
540 if(status == Z_STREAM_END) goto DblBreak;
547 (void)fclose(mat_file);
548 RelinquishMagickMemory(CacheBlock);
549 RelinquishMagickMemory(DecompressBlock);
551 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
552 if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
553 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
554 if (status == MagickFalse)
556 DeleteImageFromList(&image2);
558 fclose(clone_info->file);
559 clone_info->file = NULL;
561 (void) unlink(clone_info->filename);
570 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
574 % R e a d M A T L A B i m a g e %
578 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
580 % ReadMATImage() reads an MAT X image file and returns it. It
581 % allocates the memory necessary for the new Image structure and returns a
582 % pointer to the new image.
584 % The format of the ReadMATImage method is:
586 % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
588 % A description of each parameter follows:
590 % o image: Method ReadMATImage returns a pointer to the image after
591 % reading. A null image is returned if there is a memory shortage or if
592 % the image cannot be read.
594 % o image_info: Specifies a pointer to a ImageInfo structure.
596 % o exception: return any errors or warnings in this structure.
600 static inline size_t MagickMin(const size_t x,const size_t y)
607 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
609 Image *image, *image2=NULL,
614 MATHeader MATLAB_HDR;
617 QuantumInfo *quantum_info;
618 ImageInfo *clone_info;
621 unsigned char *BImgBuff = NULL;
622 double MinVal, MaxVal;
627 MagickOffsetType filepos=0x80;
631 unsigned int (*ReadBlobXXXLong)(Image *image);
632 unsigned short (*ReadBlobXXXShort)(Image *image);
633 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
634 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
637 assert(image_info != (const ImageInfo *) NULL);
638 assert(image_info->signature == MagickSignature);
639 assert(exception != (ExceptionInfo *) NULL);
640 assert(exception->signature == MagickSignature);
641 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
646 image = AcquireImage(image_info);
648 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
649 if (status == MagickFalse)
651 image=DestroyImageList(image);
652 return((Image *) NULL);
657 clone_info=CloneImageInfo(image_info);
658 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
659 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
660 MATLAB_HDR.Version = ReadBlobLSBShort(image);
661 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
662 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
664 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
665 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
666 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
668 ReadBlobXXXLong = ReadBlobLSBLong;
669 ReadBlobXXXShort = ReadBlobLSBShort;
670 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
671 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
672 image->endian = LSBEndian;
674 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
676 ReadBlobXXXLong = ReadBlobMSBLong;
677 ReadBlobXXXShort = ReadBlobMSBShort;
678 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
679 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
680 image->endian = MSBEndian;
683 goto MATLAB_KO; /* unsupported endian */
685 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
686 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
688 filepos = TellBlob(image);
689 while(!EOFBlob(image)) /* object parser loop */
691 (void) SeekBlob(image,filepos,SEEK_SET);
692 /* printf("pos=%X\n",TellBlob(image)); */
694 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
695 if(EOFBlob(image)) break;
696 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
697 if(EOFBlob(image)) break;
698 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
701 #if defined(MAGICKCORE_ZLIB_DELEGATE)
702 if(MATLAB_HDR.DataType == miCOMPRESSED)
704 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
705 if(image2==NULL) continue;
706 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
710 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
712 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
713 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
715 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
716 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
717 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
719 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
721 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
722 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
723 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
724 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
725 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
728 switch(MATLAB_HDR.DimFlag)
730 case 8: z=1; break; /* 2D matrix*/
731 case 12: z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
732 Unknown6 = ReadBlobXXXLong(image2);
734 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
736 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
739 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
740 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
742 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
743 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
744 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
745 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
746 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
747 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
748 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
749 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
750 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
751 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
752 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
753 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
754 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
755 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
757 switch (MATLAB_HDR.NameFlag)
760 size = ReadBlobXXXLong(image2); /* Object name string size */
761 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
762 (void) SeekBlob(image2, size, SEEK_CUR);
768 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
774 CellType = ReadBlobXXXLong(image2); /* Additional object type */
776 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
777 "MATLAB_HDR.CellType: %.20g",(double) CellType);
779 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
781 /* Image is gray when no complex flag is set and 2D Matrix */
782 if ((MATLAB_HDR.DimFlag == 8) &&
783 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
784 image->type=GrayscaleType;
791 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
794 image->depth = 8; /* Byte type cell */
795 ldblk = (ssize_t) MATLAB_HDR.SizeX;
800 image->depth = 16; /* Word type cell */
801 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
806 image->depth = 32; /* Dword type cell */
807 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
812 image->depth = 64; /* Qword type cell */
813 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
817 image->depth = 32; /* double type cell */
818 (void) SetImageOption(clone_info,"quantum:format","floating-point");
819 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
820 { /* complex float type cell */
822 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
826 image->depth = 64; /* double type cell */
827 (void) SetImageOption(clone_info,"quantum:format","floating-point");
828 if (sizeof(double) != 8)
829 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
830 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
831 { /* complex double type cell */
833 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
836 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
839 image->columns = MATLAB_HDR.SizeX;
840 image->rows = MATLAB_HDR.SizeY;
841 quantum_info=AcquireQuantumInfo(clone_info,image);
842 if (quantum_info == (QuantumInfo *) NULL)
843 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
845 image->colors = one << image->depth;
846 if (image->columns == 0 || image->rows == 0)
849 /* ----- Create gray palette ----- */
851 if (CellType==miUINT8 && z!=3)
853 if(image->colors>256) image->colors = 256;
855 if (!AcquireImageColormap(image, image->colors))
857 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
861 If ping is true, then only set image size and colors without
862 reading any image data.
864 if (image_info->ping)
866 size_t temp = image->columns;
867 image->columns = image->rows;
869 goto done_reading; /* !!!!!! BAD !!!! */
872 /* ----- Load raster data ----- */
873 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
874 if (BImgBuff == NULL)
879 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
881 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
884 /* Main loop for reading all scanlines */
885 if(z==1) z=0; /* read grey scanlines */
886 /* else read color scanlines */
889 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
891 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
892 if (q == (const Quantum *)NULL)
894 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
895 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
896 goto done_reading; /* Skip image rotation, when cannot set image pixels */
898 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
900 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
901 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
904 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
906 FixLogical((unsigned char *)BImgBuff,ldblk);
907 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
909 ImportQuantumPixelsFailed:
910 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
911 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
917 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
918 goto ImportQuantumPixelsFailed;
921 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
922 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
923 FixSignedValues(image,q,MATLAB_HDR.SizeX);
926 if (!SyncAuthenticPixels(image,exception))
928 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
929 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
937 /* Read complex part of numbers here */
938 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
939 { /* Find Min and Max Values for complex parts of floats */
940 CellType = ReadBlobXXXLong(image2); /* Additional object type */
941 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
943 if (CellType==miDOUBLE || CellType==miSINGLE)
945 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
948 if (CellType==miDOUBLE)
949 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
951 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
952 InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
955 if (CellType==miSINGLE)
956 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
958 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
959 InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
963 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
964 if ((MATLAB_HDR.DimFlag == 8) &&
965 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
966 image->type=GrayscaleType;
967 if (image->depth == 1)
968 image->type=BilevelType;
971 image2 = NULL; /* Remove shadow copy to an image before rotation. */
974 rotated_image = RotateImage(image, 90.0, exception);
975 if (rotated_image != (Image *) NULL)
977 /* Remove page offsets added by RotateImage */
978 rotated_image->page.x=0;
979 rotated_image->page.y=0;
981 blob = rotated_image->blob;
982 rotated_image->blob = image->blob;
983 rotated_image->colors = image->colors;
985 AppendImageToList(&image,rotated_image);
986 DeleteImageFromList(&image);
994 DeleteImageFromList(&image2);
999 fclose(clone_info->file);
1000 clone_info->file = NULL;
1001 (void) unlink(clone_info->filename);
1006 /* Allocate next image structure. */
1007 AcquireNextImage(image_info,image);
1008 if (image->next == (Image *) NULL) break;
1009 image=SyncNextImageInList(image);
1010 image->columns=image->rows=0;
1013 /* row scan buffer is no longer needed */
1014 RelinquishMagickMemory(BImgBuff);
1017 clone_info=DestroyImageInfo(clone_info);
1019 RelinquishMagickMemory(BImgBuff);
1028 Rewind list, removing any empty images while rewinding.
1032 while (p != (Image *)NULL)
1035 if ((p->rows == 0) || (p->columns == 0)) {
1037 DeleteImageFromList(&tmp);
1047 for (p=image; p != (Image *) NULL; p=p->next)
1051 if(clone_info != NULL) /* cleanup garbage file from compression */
1053 if(clone_info->file)
1055 fclose(clone_info->file);
1056 clone_info->file = NULL;
1057 (void) unlink(clone_info->filename);
1059 DestroyImageInfo(clone_info);
1062 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1064 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1069 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1073 % R e g i s t e r M A T I m a g e %
1077 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1079 % Method RegisterMATImage adds attributes for the MAT image format to
1080 % the list of supported formats. The attributes include the image format
1081 % tag, a method to read and/or write the format, whether the format
1082 % supports the saving of more than one frame to the same file or blob,
1083 % whether the format supports native in-memory I/O, and a brief
1084 % description of the format.
1086 % The format of the RegisterMATImage method is:
1088 % size_t RegisterMATImage(void)
1091 ModuleExport size_t RegisterMATImage(void)
1096 entry=SetMagickInfo("MAT");
1097 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1098 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1099 entry->blob_support=MagickFalse;
1100 entry->seekable_stream=MagickTrue;
1101 entry->description=AcquireString("MATLAB level 5 image format");
1102 entry->module=AcquireString("MAT");
1103 (void) RegisterMagickInfo(entry);
1104 return(MagickImageCoderSignature);
1108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1112 % U n r e g i s t e r M A T I m a g e %
1116 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1118 % Method UnregisterMATImage removes format registrations made by the
1119 % MAT module from the list of supported formats.
1121 % The format of the UnregisterMATImage method is:
1123 % UnregisterMATImage(void)
1126 ModuleExport void UnregisterMATImage(void)
1128 (void) UnregisterMagickInfo("MAT");
1132 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1136 % W r i t e M A T L A B I m a g e %
1140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1142 % Function WriteMATImage writes an Matlab matrix to a file.
1144 % The format of the WriteMATImage method is:
1146 % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
1148 % A description of each parameter follows.
1150 % o status: Function WriteMATImage return True if the image is written.
1151 % False is returned is there is a memory shortage or if the image file
1154 % o image_info: Specifies a pointer to a ImageInfo structure.
1156 % o image: A pointer to an Image structure.
1159 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
1166 register const Quantum *p;
1168 unsigned int status;
1172 char MATLAB_HDR[0x80];
1173 time_t current_time;
1174 struct tm local_time;
1175 unsigned char *pixels;
1185 Open output image file.
1187 assert(image_info != (const ImageInfo *) NULL);
1188 assert(image_info->signature == MagickSignature);
1189 assert(image != (Image *) NULL);
1190 assert(image->signature == MagickSignature);
1191 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1193 status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->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,&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 exception=(&image->exception);
1255 quantum_info=AcquireQuantumInfo(image_info,image);
1256 if (quantum_info == (QuantumInfo *) NULL)
1257 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1258 pixels=GetQuantumPixels(quantum_info);
1261 for (y=0; y < (ssize_t)image->columns; y++)
1263 p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
1264 if (p == (const Quantum *) NULL)
1266 (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1267 z2qtype[z],pixels,exception);
1268 (void) WriteBlob(image,image->rows,pixels);
1270 if (!SyncAuthenticPixels(image,exception))
1273 while(padding-->0) (void) WriteBlobByte(image,0);
1274 quantum_info=DestroyQuantumInfo(quantum_info);
1275 if (GetNextImageInList(image) == (Image *) NULL)
1277 image=SyncNextImageInList(image);
1278 status=SetImageProgress(image,SaveImagesTag,scene++,
1279 GetImageListLength(image));
1280 if (status == MagickFalse)
1282 } while (image_info->adjoin != MagickFalse);
1283 (void) CloseBlob(image);