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/distort.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/image.h"
62 #include "MagickCore/image-private.h"
63 #include "MagickCore/list.h"
64 #include "MagickCore/magick.h"
65 #include "MagickCore/memory_.h"
66 #include "MagickCore/monitor.h"
67 #include "MagickCore/monitor-private.h"
68 #include "MagickCore/pixel-accessor.h"
69 #include "MagickCore/quantum-private.h"
70 #include "MagickCore/option.h"
71 #include "MagickCore/pixel.h"
72 #include "MagickCore/resource_.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(Image *image,double *p,int y,double MinVal,
182 double MaxVal,ExceptionInfo *exception)
194 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
195 if (q == (Quantum *) NULL)
197 for (x = 0; x < (ssize_t) image->columns; x++)
201 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
202 if (f + GetPixelRed(image,q) > QuantumRange)
203 SetPixelRed(image,QuantumRange,q);
205 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
206 if ((int) f / 2.0 > GetPixelGreen(image,q))
208 SetPixelGreen(image,0,q);
209 SetPixelBlue(image,0,q);
213 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
214 SetPixelGreen(image,GetPixelBlue(image,q),q);
219 f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));
220 if (f+GetPixelBlue(image,q) > QuantumRange)
221 SetPixelBlue(image,QuantumRange,q);
223 SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);
224 if ((int) f / 2.0 > GetPixelGreen(image,q))
226 SetPixelRed(image,0,q);
227 SetPixelGreen(image,0,q);
231 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
232 SetPixelGreen(image,GetPixelRed(image,q),q);
236 q+=GetPixelChannels(image);
238 if (!SyncAuthenticPixels(image,exception))
244 static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
245 double MaxVal,ExceptionInfo *exception)
256 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
257 if (q == (Quantum *) NULL)
259 for (x = 0; x < (ssize_t) image->columns; x++)
263 f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));
264 if (f+GetPixelRed(image,q) > QuantumRange)
265 SetPixelRed(image,QuantumRange,q);
267 SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);
268 if ((int) f / 2.0 > GetPixelGreen(image,q))
270 SetPixelGreen(image,0,q);
271 SetPixelBlue(image,0,q);
275 SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);
276 SetPixelGreen(image,GetPixelBlue(image,q),q);
281 f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));
282 if (f + GetPixelBlue(image,q) > QuantumRange)
283 SetPixelBlue(image,QuantumRange,q);
285 SetPixelBlue(image,GetPixelBlue(image,q)+
287 if ((int) f / 2.0 > GetPixelGreen(image,q))
289 SetPixelGreen(image,0,q);
290 SetPixelRed(image,0,q);
294 SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);
295 SetPixelGreen(image,GetPixelRed(image,q),q);
301 if (!SyncAuthenticPixels(image,exception))
307 /************** READERS ******************/
309 /* This function reads one block of floats*/
310 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
314 *data++ = ReadBlobFloat(image);
315 len -= sizeof(float);
318 (void) SeekBlob(image, len, SEEK_CUR);
321 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
325 *data++ = ReadBlobFloat(image);
326 len -= sizeof(float);
329 (void) SeekBlob(image, len, SEEK_CUR);
332 /* This function reads one block of doubles*/
333 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
337 *data++ = ReadBlobDouble(image);
338 len -= sizeof(double);
341 (void) SeekBlob(image, len, SEEK_CUR);
344 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
348 *data++ = ReadBlobDouble(image);
349 len -= sizeof(double);
352 (void) SeekBlob(image, len, SEEK_CUR);
355 /* Calculate minimum and maximum from a given block of data */
356 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
358 MagickOffsetType filepos;
360 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
361 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
365 if (endian_indicator == LSBEndian)
367 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
368 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
372 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
373 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
376 filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
377 for (i = 0; i < SizeY; i++)
379 if (CellType==miDOUBLE)
381 ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
382 dblrow = (double *)BImgBuff;
385 *Min = *Max = *dblrow;
387 for (x = 0; x < SizeX; x++)
396 if (CellType==miSINGLE)
398 ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
399 fltrow = (float *)BImgBuff;
402 *Min = *Max = *fltrow;
404 for (x = 0; x < (ssize_t) SizeX; x++)
414 (void) SeekBlob(image, filepos, SEEK_SET);
418 static void FixSignedValues(const Image *image,Quantum *q, int y)
422 /* Please note that negative values will overflow
423 Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
424 <-1;-128> + 127+1 = <0; 127> */
425 SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
426 SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
427 SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
433 /** Fix whole row of logical/binary data. It means pack it. */
434 static void FixLogical(unsigned char *Buff,int ldblk)
436 unsigned char mask=128;
437 unsigned char *BuffL = Buff;
438 unsigned char val = 0;
457 #if defined(MAGICKCORE_ZLIB_DELEGATE)
458 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
462 return((voidpf) AcquireQuantumMemory(items,size));
465 static void RelinquishZIPMemory(voidpf context,voidpf memory)
468 memory=RelinquishMagickMemory(memory);
472 #if defined(MAGICKCORE_ZLIB_DELEGATE)
473 /** This procedure decompreses an image block for a new MATLAB format. */
474 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
478 void *CacheBlock, *DecompressBlock;
486 if(clone_info==NULL) return NULL;
487 if(clone_info->file) /* Close file opened from previous transaction. */
489 fclose(clone_info->file);
490 clone_info->file = NULL;
491 (void) remove_utf8(clone_info->filename);
494 CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
495 if(CacheBlock==NULL) return NULL;
496 DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
497 if(DecompressBlock==NULL)
499 RelinquishMagickMemory(CacheBlock);
503 mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
506 RelinquishMagickMemory(CacheBlock);
507 RelinquishMagickMemory(DecompressBlock);
508 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
512 zip_info.zalloc=AcquireZIPMemory;
513 zip_info.zfree=RelinquishZIPMemory;
514 zip_info.opaque = (voidpf) NULL;
515 inflateInit(&zip_info);
516 /* zip_info.next_out = 8*4;*/
518 zip_info.avail_in = 0;
519 zip_info.total_out = 0;
520 while(Size>0 && !EOFBlob(orig))
522 magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
523 zip_info.next_in = (Bytef *) CacheBlock;
524 zip_info.avail_in = (uInt) magick_size;
526 while(zip_info.avail_in>0)
528 zip_info.avail_out = 4096;
529 zip_info.next_out = (Bytef *) DecompressBlock;
530 status = inflate(&zip_info,Z_NO_FLUSH);
531 extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
534 if(status == Z_STREAM_END) goto DblBreak;
541 (void)fclose(mat_file);
542 RelinquishMagickMemory(CacheBlock);
543 RelinquishMagickMemory(DecompressBlock);
545 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
546 if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;
547 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
548 if (status == MagickFalse)
550 DeleteImageFromList(&image2);
552 fclose(clone_info->file);
553 clone_info->file = NULL;
555 (void) remove_utf8(clone_info->filename);
564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
568 % R e a d M A T L A B i m a g e %
572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
574 % ReadMATImage() reads an MAT X image file and returns it. It
575 % allocates the memory necessary for the new Image structure and returns a
576 % pointer to the new image.
578 % The format of the ReadMATImage method is:
580 % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
582 % A description of each parameter follows:
584 % o image: Method ReadMATImage returns a pointer to the image after
585 % reading. A null image is returned if there is a memory shortage or if
586 % the image cannot be read.
588 % o image_info: Specifies a pointer to a ImageInfo structure.
590 % o exception: return any errors or warnings in this structure.
594 static inline size_t MagickMin(const size_t x,const size_t y)
601 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
603 Image *image, *image2=NULL,
608 MATHeader MATLAB_HDR;
611 QuantumInfo *quantum_info;
612 ImageInfo *clone_info;
615 unsigned char *BImgBuff = NULL;
616 double MinVal, MaxVal;
621 MagickOffsetType filepos=0x80;
625 unsigned int (*ReadBlobXXXLong)(Image *image);
626 unsigned short (*ReadBlobXXXShort)(Image *image);
627 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
628 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
631 assert(image_info != (const ImageInfo *) NULL);
632 assert(image_info->signature == MagickSignature);
633 assert(exception != (ExceptionInfo *) NULL);
634 assert(exception->signature == MagickSignature);
635 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
640 image = AcquireImage(image_info,exception);
642 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
643 if (status == MagickFalse)
645 image=DestroyImageList(image);
646 return((Image *) NULL);
651 clone_info=CloneImageInfo(image_info);
652 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
653 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
654 MATLAB_HDR.Version = ReadBlobLSBShort(image);
655 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
656 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
658 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
659 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
660 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
662 ReadBlobXXXLong = ReadBlobLSBLong;
663 ReadBlobXXXShort = ReadBlobLSBShort;
664 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
665 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
666 image->endian = LSBEndian;
668 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
670 ReadBlobXXXLong = ReadBlobMSBLong;
671 ReadBlobXXXShort = ReadBlobMSBShort;
672 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
673 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
674 image->endian = MSBEndian;
677 goto MATLAB_KO; /* unsupported endian */
679 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
680 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
682 filepos = TellBlob(image);
683 while(!EOFBlob(image)) /* object parser loop */
686 (void) SeekBlob(image,filepos,SEEK_SET);
687 /* printf("pos=%X\n",TellBlob(image)); */
689 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
690 if(EOFBlob(image)) break;
691 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
692 if(EOFBlob(image)) break;
693 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
696 #if defined(MAGICKCORE_ZLIB_DELEGATE)
697 if(MATLAB_HDR.DataType == miCOMPRESSED)
699 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
700 if(image2==NULL) continue;
701 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
705 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
707 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
708 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
710 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
711 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
712 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
714 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
716 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
717 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
718 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
719 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
720 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
723 switch(MATLAB_HDR.DimFlag)
725 case 8: z2=z=1; break; /* 2D matrix*/
726 case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
727 (void) ReadBlobXXXLong(image2);
728 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
730 case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
732 ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
733 Frames = ReadBlobXXXLong(image2);
735 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
738 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
739 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
741 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
742 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
743 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
744 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
745 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
746 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
747 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
748 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
749 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
750 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
751 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
752 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
753 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
754 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
756 switch (MATLAB_HDR.NameFlag)
759 size = ReadBlobXXXLong(image2); /* Object name string size */
760 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
761 (void) SeekBlob(image2, size, SEEK_CUR);
767 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
773 CellType = ReadBlobXXXLong(image2); /* Additional object type */
775 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
776 "MATLAB_HDR.CellType: %.20g",(double) CellType);
778 (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))
785 image->type=GrayscaleType;
786 image->colorspace=GRAYColorspace;
794 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
797 image->depth = 8; /* Byte type cell */
798 ldblk = (ssize_t) MATLAB_HDR.SizeX;
803 image->depth = 16; /* Word type cell */
804 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
809 image->depth = 32; /* Dword type cell */
810 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
815 image->depth = 64; /* Qword type cell */
816 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
820 image->depth = 32; /* double type cell */
821 (void) SetImageOption(clone_info,"quantum:format","floating-point");
822 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
823 { /* complex float type cell */
825 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
829 image->depth = 64; /* double type cell */
830 (void) SetImageOption(clone_info,"quantum:format","floating-point");
831 if (sizeof(double) != 8)
832 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
833 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
834 { /* complex double type cell */
836 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
839 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
842 image->columns = MATLAB_HDR.SizeX;
843 image->rows = MATLAB_HDR.SizeY;
844 quantum_info=AcquireQuantumInfo(clone_info,image);
845 if (quantum_info == (QuantumInfo *) NULL)
846 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
848 image->colors = one << image->depth;
849 if (image->columns == 0 || image->rows == 0)
852 /* ----- Create gray palette ----- */
854 if (CellType==miUINT8 && z!=3)
856 if(image->colors>256) image->colors = 256;
858 if (AcquireImageColormap(image, image->colors,exception) == MagickFalse)
860 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
864 If ping is true, then only set image size and colors without
865 reading any image data.
867 if (image_info->ping)
869 size_t temp = image->columns;
870 image->columns = image->rows;
872 goto done_reading; /* !!!!!! BAD !!!! */
875 /* ----- Load raster data ----- */
876 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
877 if (BImgBuff == NULL)
882 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
884 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
887 /* Main loop for reading all scanlines */
888 if(z==1) z=0; /* read grey scanlines */
889 /* else read color scanlines */
892 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
894 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
895 if (q == (Quantum *)NULL)
897 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
898 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
899 goto done_reading; /* Skip image rotation, when cannot set image pixels */
901 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
903 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
904 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
907 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
909 FixLogical((unsigned char *)BImgBuff,ldblk);
910 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
912 ImportQuantumPixelsFailed:
913 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
914 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
920 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
921 goto ImportQuantumPixelsFailed;
924 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
925 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
926 FixSignedValues(image,q,MATLAB_HDR.SizeX);
929 if (!SyncAuthenticPixels(image,exception))
931 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
932 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
940 /* Read complex part of numbers here */
941 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
942 { /* Find Min and Max Values for complex parts of floats */
943 CellType = ReadBlobXXXLong(image2); /* Additional object type */
944 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
946 if (CellType==miDOUBLE || CellType==miSINGLE)
948 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
951 if (CellType==miDOUBLE)
952 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
954 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
955 InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
959 if (CellType==miSINGLE)
960 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
962 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
963 InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
968 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
969 if ((MATLAB_HDR.DimFlag == 8) &&
970 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
971 image->type=GrayscaleType;
972 if (image->depth == 1)
973 image->type=BilevelType;
976 image2 = NULL; /* Remove shadow copy to an image before rotation. */
979 rotated_image = RotateImage(image, 90.0, exception);
980 if (rotated_image != (Image *) NULL)
982 /* Remove page offsets added by RotateImage */
983 rotated_image->page.x=0;
984 rotated_image->page.y=0;
986 blob = rotated_image->blob;
987 rotated_image->blob = image->blob;
988 rotated_image->colors = image->colors;
990 AppendImageToList(&image,rotated_image);
991 DeleteImageFromList(&image);
999 DeleteImageFromList(&image2);
1002 if(clone_info->file)
1004 fclose(clone_info->file);
1005 clone_info->file = NULL;
1006 (void) remove_utf8(clone_info->filename);
1011 /* Allocate next image structure. */
1012 AcquireNextImage(image_info,image,exception);
1013 if (image->next == (Image *) NULL) break;
1014 image=SyncNextImageInList(image);
1015 image->columns=image->rows=0;
1018 /* row scan buffer is no longer needed */
1019 RelinquishMagickMemory(BImgBuff);
1025 if(image2==NULL) image2 = image;
1028 if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */
1030 /* CloseBlob(image2); */
1031 DeleteImageFromList(&image2);
1034 if(clone_info->file)
1036 fclose(clone_info->file);
1037 clone_info->file = NULL;
1038 (void) remove_utf8(clone_info->filename);
1042 clone_info=DestroyImageInfo(clone_info);
1045 RelinquishMagickMemory(BImgBuff);
1054 Rewind list, removing any empty images while rewinding.
1058 while (p != (Image *)NULL)
1061 if ((p->rows == 0) || (p->columns == 0)) {
1063 DeleteImageFromList(&tmp);
1073 for (p=image; p != (Image *) NULL; p=p->next)
1077 if(clone_info != NULL) /* cleanup garbage file from compression */
1079 if(clone_info->file)
1081 fclose(clone_info->file);
1082 clone_info->file = NULL;
1083 (void) remove_utf8(clone_info->filename);
1085 DestroyImageInfo(clone_info);
1088 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1090 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1095 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1099 % R e g i s t e r M A T I m a g e %
1103 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1105 % Method RegisterMATImage adds attributes for the MAT image format to
1106 % the list of supported formats. The attributes include the image format
1107 % tag, a method to read and/or write the format, whether the format
1108 % supports the saving of more than one frame to the same file or blob,
1109 % whether the format supports native in-memory I/O, and a brief
1110 % description of the format.
1112 % The format of the RegisterMATImage method is:
1114 % size_t RegisterMATImage(void)
1117 ModuleExport size_t RegisterMATImage(void)
1122 entry=SetMagickInfo("MAT");
1123 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1124 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1125 entry->blob_support=MagickFalse;
1126 entry->seekable_stream=MagickTrue;
1127 entry->description=AcquireString("MATLAB level 5 image format");
1128 entry->module=AcquireString("MAT");
1129 (void) RegisterMagickInfo(entry);
1130 return(MagickImageCoderSignature);
1134 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1138 % U n r e g i s t e r M A T I m a g e %
1142 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1144 % Method UnregisterMATImage removes format registrations made by the
1145 % MAT module from the list of supported formats.
1147 % The format of the UnregisterMATImage method is:
1149 % UnregisterMATImage(void)
1152 ModuleExport void UnregisterMATImage(void)
1154 (void) UnregisterMagickInfo("MAT");
1158 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1162 % W r i t e M A T L A B I m a g e %
1166 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1168 % Function WriteMATImage writes an Matlab matrix to a file.
1170 % The format of the WriteMATImage method is:
1172 % MagickBooleanType WriteMATImage(const ImageInfo *image_info,
1173 % Image *image,ExceptionInfo *exception)
1175 % A description of each parameter follows.
1177 % o image_info: Specifies a pointer to a ImageInfo structure.
1179 % o image: A pointer to an Image structure.
1181 % o exception: return any errors or warnings in this structure.
1184 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
1185 ExceptionInfo *exception)
1189 register const Quantum *p;
1191 unsigned int status;
1195 char MATLAB_HDR[0x80];
1196 time_t current_time;
1197 struct tm local_time;
1198 unsigned char *pixels;
1208 Open output image file.
1210 assert(image_info != (const ImageInfo *) NULL);
1211 assert(image_info->signature == MagickSignature);
1212 assert(image != (Image *) NULL);
1213 assert(image->signature == MagickSignature);
1214 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1216 assert(exception != (ExceptionInfo *) NULL);
1217 assert(exception->signature == MagickSignature);
1218 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1219 if (status == MagickFalse)
1220 return(MagickFalse);
1223 current_time=time((time_t *) NULL);
1224 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1225 (void) localtime_r(¤t_time,&local_time);
1227 (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
1229 (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1230 FormatLocaleString(MATLAB_HDR,MaxTextExtent,"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1231 OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1232 local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1233 local_time.tm_sec,local_time.tm_year+1900);
1236 MATLAB_HDR[0x7E]='I';
1237 MATLAB_HDR[0x7F]='M';
1238 (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1242 if (IssRGBColorspace(image->colorspace) == MagickFalse)
1243 (void) TransformImageColorspace(image,sRGBColorspace,exception);
1245 is_gray = IsImageGray(image,exception);
1246 z = is_gray ? 0 : 3;
1251 DataSize = image->rows /*Y*/ * image->columns /*X*/;
1252 if(!is_gray) DataSize *= 3 /*Z*/;
1253 padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1255 (void) WriteBlobLSBLong(image, miMATRIX);
1256 (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
1257 (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1258 (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1259 (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
1260 (void) WriteBlobLSBLong(image, 0);
1261 (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1262 (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
1263 (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
1264 (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
1267 (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
1268 (void) WriteBlobLSBLong(image, 0);
1270 (void) WriteBlobLSBShort(image, 1); /* 0xB0 */
1271 (void) WriteBlobLSBShort(image, 1); /* 0xB2 */
1272 (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1273 (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
1274 (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
1279 quantum_info=AcquireQuantumInfo(image_info,image);
1280 if (quantum_info == (QuantumInfo *) NULL)
1281 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1282 pixels=GetQuantumPixels(quantum_info);
1285 for (y=0; y < (ssize_t)image->columns; y++)
1287 p=GetVirtualPixels(image,y,0,1,image->rows,exception);
1288 if (p == (const Quantum *) NULL)
1290 (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1291 z2qtype[z],pixels,exception);
1292 (void) WriteBlob(image,image->rows,pixels);
1294 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1297 while(padding-->0) (void) WriteBlobByte(image,0);
1298 quantum_info=DestroyQuantumInfo(quantum_info);
1299 if (GetNextImageInList(image) == (Image *) NULL)
1301 image=SyncNextImageInList(image);
1302 status=SetImageProgress(image,SaveImagesTag,scene++,
1303 GetImageListLength(image));
1304 if (status == MagickFalse)
1306 } while (image_info->adjoin != MagickFalse);
1307 (void) CloseBlob(image);