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 "magick/studio.h"
51 #include "magick/blob.h"
52 #include "magick/blob-private.h"
53 #include "magick/cache.h"
54 #include "magick/color-private.h"
55 #include "magick/colormap.h"
56 #include "magick/exception.h"
57 #include "magick/exception-private.h"
58 #include "magick/image.h"
59 #include "magick/image-private.h"
60 #include "magick/list.h"
61 #include "magick/magick.h"
62 #include "magick/memory_.h"
63 #include "magick/monitor.h"
64 #include "magick/monitor-private.h"
65 #include "magick/quantum-private.h"
66 #include "magick/option.h"
67 #include "magick/resource_.h"
68 #include "magick/shear.h"
69 #include "magick/static.h"
70 #include "magick/string_.h"
71 #include "magick/module.h"
72 #include "magick/transform.h"
73 #if defined(MAGICKCORE_ZLIB_DELEGATE)
80 static MagickBooleanType
81 WriteMATImage(const ImageInfo *,Image *);
84 /* Auto coloring method, sorry this creates some artefact inside data
85 MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
86 MinReal+j*0 = white MaxReal+j*0 = black
87 MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
93 unsigned short Version;
94 char EndianIndicator[2];
95 unsigned long DataType;
96 unsigned long ObjectSize;
97 unsigned long unknown1;
98 unsigned long unknown2;
100 unsigned short unknown5;
101 unsigned char StructureFlag;
102 unsigned char StructureClass;
103 unsigned long unknown3;
104 unsigned long unknown4;
105 unsigned long DimFlag;
109 unsigned short Flag1;
110 unsigned short NameFlag;
114 static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
115 static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
116 static const char *OsDesc=
129 miINT8 = 1, /* 8 bit signed */
130 miUINT8, /* 8 bit unsigned */
131 miINT16, /* 16 bit signed */
132 miUINT16, /* 16 bit unsigned */
133 miINT32, /* 32 bit signed */
134 miUINT32, /* 32 bit unsigned */
135 miSINGLE, /* IEEE 754 single precision float */
137 miDOUBLE, /* IEEE 754 double precision float */
140 miINT64, /* 64 bit signed */
141 miUINT64, /* 64 bit unsigned */
142 miMATRIX, /* MATLAB array */
143 miCOMPRESSED, /* Compressed Data */
144 miUTF8, /* Unicode UTF-8 Encoded Character Data */
145 miUTF16, /* Unicode UTF-16 Encoded Character Data */
146 miUTF32 /* Unicode UTF-32 Encoded Character Data */
151 mxCELL_CLASS=1, /* cell array */
152 mxSTRUCT_CLASS, /* structure */
153 mxOBJECT_CLASS, /* object */
154 mxCHAR_CLASS, /* character array */
155 mxSPARSE_CLASS, /* sparse array */
156 mxDOUBLE_CLASS, /* double precision array */
157 mxSINGLE_CLASS, /* single precision floating point */
158 mxINT8_CLASS, /* 8 bit signed integer */
159 mxUINT8_CLASS, /* 8 bit unsigned integer */
160 mxINT16_CLASS, /* 16 bit signed integer */
161 mxUINT16_CLASS, /* 16 bit unsigned integer */
162 mxINT32_CLASS, /* 32 bit signed integer */
163 mxUINT32_CLASS, /* 32 bit unsigned integer */
164 mxINT64_CLASS, /* 64 bit signed integer */
165 mxUINT64_CLASS, /* 64 bit unsigned integer */
166 mxFUNCTION_CLASS /* Function handle */
169 #define FLAG_COMPLEX 0x8
170 #define FLAG_GLOBAL 0x4
171 #define FLAG_LOGICAL 0x2
173 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
176 static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
184 register PixelPacket *q;
191 exception=(&image->exception);
192 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
193 if (q == (PixelPacket *) NULL)
195 for (x = 0; x < (ssize_t) image->columns; x++)
199 f = (*p / MaxVal) * (QuantumRange - q->red);
200 if (f + q->red > QuantumRange)
201 q->red = QuantumRange;
204 if ((int) f / 2.0 > q->green)
205 q->green = q->blue = 0;
207 q->green = q->blue -= (int) (f / 2.0);
211 f = (*p / MaxVal) * (QuantumRange - q->blue);
212 if (f + q->blue > QuantumRange)
213 q->blue = QuantumRange;
216 if ((int) f / 2.0 > q->green)
217 q->green = q->red = 0;
219 q->green = q->red -= (int) (f / 2.0);
224 if (!SyncAuthenticPixels(image,exception))
230 static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
238 register PixelPacket *q;
245 exception=(&image->exception);
246 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
247 if (q == (PixelPacket *) NULL)
249 for (x = 0; x < (ssize_t) image->columns; x++)
253 f = (*p / MaxVal) * (QuantumRange - q->red);
254 if (f + q->red > QuantumRange)
255 q->red = QuantumRange;
258 if ((int) f / 2.0 > q->green)
259 q->green = q->blue = 0;
261 q->green = q->blue -= (int) (f / 2.0);
265 f = (*p / MaxVal) * (QuantumRange - q->blue);
266 if (f + q->blue > QuantumRange)
267 q->blue = QuantumRange;
270 if ((int) f / 2.0 > q->green)
271 q->green = q->red = 0;
273 q->green = q->red -= (int) (f / 2.0);
278 if (!SyncAuthenticPixels(image,exception))
284 /************** READERS ******************/
286 /* This function reads one block of floats*/
287 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
291 *data++ = ReadBlobFloat(image);
292 len -= sizeof(float);
295 (void) SeekBlob(image, len, SEEK_CUR);
298 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
302 *data++ = ReadBlobFloat(image);
303 len -= sizeof(float);
306 (void) SeekBlob(image, len, SEEK_CUR);
309 /* This function reads one block of doubles*/
310 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
314 *data++ = ReadBlobDouble(image);
315 len -= sizeof(double);
318 (void) SeekBlob(image, len, SEEK_CUR);
321 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
325 *data++ = ReadBlobDouble(image);
326 len -= sizeof(double);
329 (void) SeekBlob(image, len, SEEK_CUR);
332 /* Calculate minimum and maximum from a given block of data */
333 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
335 MagickOffsetType filepos;
337 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
338 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
342 if (endian_indicator == LSBEndian)
344 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
345 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
349 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
350 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
353 filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
354 for (i = 0; i < SizeY; i++)
356 if (CellType==miDOUBLE)
358 ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
359 dblrow = (double *)BImgBuff;
362 *Min = *Max = *dblrow;
364 for (x = 0; x < SizeX; x++)
373 if (CellType==miSINGLE)
375 ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
376 fltrow = (float *)BImgBuff;
379 *Min = *Max = *fltrow;
381 for (x = 0; x < (ssize_t) SizeX; x++)
391 (void) SeekBlob(image, filepos, SEEK_SET);
395 static void FixSignedValues(PixelPacket *q, int y)
399 /* Please note that negative values will overflow
400 Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
401 <-1;-128> + 127+1 = <0; 127> */
402 q->red += QuantumRange/2 + 1;
403 q->green += QuantumRange/ + 1;
404 q->blue += QuantumRange/ + 1;
410 /** Fix whole row of logical/binary data. It means pack it. */
411 static void FixLogical(unsigned char *Buff,int ldblk)
413 unsigned char mask=128;
414 unsigned char *BuffL = Buff;
415 unsigned char val = 0;
434 #if defined(MAGICKCORE_ZLIB_DELEGATE)
435 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
439 return((voidpf) AcquireQuantumMemory(items,size));
442 static void RelinquishZIPMemory(voidpf context,voidpf memory)
445 memory=RelinquishMagickMemory(memory);
449 #if defined(MAGICKCORE_ZLIB_DELEGATE)
450 /** This procedure decompreses an image block for a new MATLAB format. */
451 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
455 void *CacheBlock, *DecompressBlock;
463 if(clone_info==NULL) return NULL;
464 if(clone_info->file) /* Close file opened from previous transaction. */
466 fclose(clone_info->file);
467 clone_info->file = NULL;
468 (void) unlink(clone_info->filename);
471 CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
472 if(CacheBlock==NULL) return NULL;
473 DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
474 if(DecompressBlock==NULL)
476 RelinquishMagickMemory(CacheBlock);
480 mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
483 RelinquishMagickMemory(CacheBlock);
484 RelinquishMagickMemory(DecompressBlock);
485 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
489 zip_info.zalloc=AcquireZIPMemory;
490 zip_info.zfree=RelinquishZIPMemory;
491 zip_info.opaque = (voidpf) NULL;
492 inflateInit(&zip_info);
493 /* zip_info.next_out = 8*4;*/
495 zip_info.avail_in = 0;
496 zip_info.total_out = 0;
497 while(Size>0 && !EOFBlob(orig))
499 magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
500 zip_info.next_in = (Bytef *) CacheBlock;
501 zip_info.avail_in = (uInt) magick_size;
503 while(zip_info.avail_in>0)
505 zip_info.avail_out = 4096;
506 zip_info.next_out = (Bytef *) DecompressBlock;
507 status = inflate(&zip_info,Z_NO_FLUSH);
508 extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
511 if(status == Z_STREAM_END) goto DblBreak;
518 (void)fclose(mat_file);
519 RelinquishMagickMemory(CacheBlock);
520 RelinquishMagickMemory(DecompressBlock);
522 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
523 if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
524 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
525 if (status == MagickFalse)
527 DeleteImageFromList(&image2);
529 fclose(clone_info->file);
530 clone_info->file = NULL;
532 (void) unlink(clone_info->filename);
541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
545 % R e a d M A T L A B i m a g e %
549 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
551 % ReadMATImage() reads an MAT X image file and returns it. It
552 % allocates the memory necessary for the new Image structure and returns a
553 % pointer to the new image.
555 % The format of the ReadMATImage method is:
557 % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
559 % A description of each parameter follows:
561 % o image: Method ReadMATImage returns a pointer to the image after
562 % reading. A null image is returned if there is a memory shortage or if
563 % the image cannot be read.
565 % o image_info: Specifies a pointer to a ImageInfo structure.
567 % o exception: return any errors or warnings in this structure.
571 static inline size_t MagickMin(const size_t x,const size_t y)
578 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
580 Image *image, *image2=NULL,
585 MATHeader MATLAB_HDR;
588 QuantumInfo *quantum_info;
589 ImageInfo *clone_info;
592 unsigned char *BImgBuff = NULL;
593 double MinVal, MaxVal;
598 MagickOffsetType filepos=0x80;
602 unsigned int (*ReadBlobXXXLong)(Image *image);
603 unsigned short (*ReadBlobXXXShort)(Image *image);
604 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
605 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
608 assert(image_info != (const ImageInfo *) NULL);
609 assert(image_info->signature == MagickSignature);
610 assert(exception != (ExceptionInfo *) NULL);
611 assert(exception->signature == MagickSignature);
612 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
617 image = AcquireImage(image_info);
619 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
620 if (status == MagickFalse)
622 image=DestroyImageList(image);
623 return((Image *) NULL);
628 clone_info=CloneImageInfo(image_info);
629 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
630 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
631 MATLAB_HDR.Version = ReadBlobLSBShort(image);
632 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
633 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
635 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
636 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
637 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
639 ReadBlobXXXLong = ReadBlobLSBLong;
640 ReadBlobXXXShort = ReadBlobLSBShort;
641 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
642 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
643 image->endian = LSBEndian;
645 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
647 ReadBlobXXXLong = ReadBlobMSBLong;
648 ReadBlobXXXShort = ReadBlobMSBShort;
649 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
650 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
651 image->endian = MSBEndian;
654 goto MATLAB_KO; /* unsupported endian */
656 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
657 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
659 filepos = TellBlob(image);
660 while(!EOFBlob(image)) /* object parser loop */
662 (void) SeekBlob(image,filepos,SEEK_SET);
663 /* printf("pos=%X\n",TellBlob(image)); */
665 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
666 if(EOFBlob(image)) break;
667 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
668 if(EOFBlob(image)) break;
669 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
672 #if defined(MAGICKCORE_ZLIB_DELEGATE)
673 if(MATLAB_HDR.DataType == miCOMPRESSED)
675 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
676 if(image2==NULL) continue;
677 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
681 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
683 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
684 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
686 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
687 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
688 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
690 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
692 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
693 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
694 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
695 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
696 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
699 switch(MATLAB_HDR.DimFlag)
701 case 8: z=1; break; /* 2D matrix*/
702 case 12: z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
703 Unknown6 = ReadBlobXXXLong(image2);
705 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
707 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
710 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
711 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
713 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
714 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
715 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
716 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
717 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
718 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
719 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
720 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
721 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
722 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
723 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
724 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
725 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
726 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
728 switch (MATLAB_HDR.NameFlag)
731 size = ReadBlobXXXLong(image2); /* Object name string size */
732 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
733 (void) SeekBlob(image2, size, SEEK_CUR);
739 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
745 CellType = ReadBlobXXXLong(image2); /* Additional object type */
747 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
748 "MATLAB_HDR.CellType: %.20g",(double) CellType);
750 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
752 /* Image is gray when no complex flag is set and 2D Matrix */
753 if ((MATLAB_HDR.DimFlag == 8) &&
754 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
755 image->type=GrayscaleType;
762 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
765 image->depth = 8; /* Byte type cell */
766 ldblk = (ssize_t) MATLAB_HDR.SizeX;
771 image->depth = 16; /* Word type cell */
772 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
777 image->depth = 32; /* Dword type cell */
778 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
783 image->depth = 64; /* Qword type cell */
784 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
788 image->depth = 32; /* double type cell */
789 (void) SetImageOption(clone_info,"quantum:format","floating-point");
790 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
791 { /* complex float type cell */
793 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
797 image->depth = 64; /* double type cell */
798 (void) SetImageOption(clone_info,"quantum:format","floating-point");
799 if (sizeof(double) != 8)
800 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
801 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
802 { /* complex double type cell */
804 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
807 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
810 image->columns = MATLAB_HDR.SizeX;
811 image->rows = MATLAB_HDR.SizeY;
812 quantum_info=AcquireQuantumInfo(clone_info,image);
813 if (quantum_info == (QuantumInfo *) NULL)
814 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
816 image->colors = one << image->depth;
817 if (image->columns == 0 || image->rows == 0)
820 /* ----- Create gray palette ----- */
822 if (CellType==miUINT8 && z!=3)
824 if(image->colors>256) image->colors = 256;
826 if (!AcquireImageColormap(image, image->colors))
828 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
832 If ping is true, then only set image size and colors without
833 reading any image data.
835 if (image_info->ping)
837 size_t temp = image->columns;
838 image->columns = image->rows;
840 goto done_reading; /* !!!!!! BAD !!!! */
843 /* ----- Load raster data ----- */
844 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
845 if (BImgBuff == NULL)
850 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
852 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
855 /* Main loop for reading all scanlines */
856 if(z==1) z=0; /* read grey scanlines */
857 /* else read color scanlines */
860 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
862 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
863 if (q == (PixelPacket *)NULL)
865 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
866 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
867 goto done_reading; /* Skip image rotation, when cannot set image pixels */
869 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
871 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
872 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
875 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
877 FixLogical((unsigned char *)BImgBuff,ldblk);
878 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
880 ImportQuantumPixelsFailed:
881 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
882 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
888 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
889 goto ImportQuantumPixelsFailed;
892 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
893 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
894 FixSignedValues(q,MATLAB_HDR.SizeX);
897 if (!SyncAuthenticPixels(image,exception))
899 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
900 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
908 /* Read complex part of numbers here */
909 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
910 { /* Find Min and Max Values for complex parts of floats */
911 CellType = ReadBlobXXXLong(image2); /* Additional object type */
912 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
914 if (CellType==miDOUBLE || CellType==miSINGLE)
916 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
919 if (CellType==miDOUBLE)
920 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
922 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
923 InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
926 if (CellType==miSINGLE)
927 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
929 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
930 InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
934 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
935 if ((MATLAB_HDR.DimFlag == 8) &&
936 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
937 image->type=GrayscaleType;
938 if (image->depth == 1)
939 image->type=BilevelType;
942 image2 = NULL; /* Remove shadow copy to an image before rotation. */
945 rotated_image = RotateImage(image, 90.0, exception);
946 if (rotated_image != (Image *) NULL)
948 /* Remove page offsets added by RotateImage */
949 rotated_image->page.x=0;
950 rotated_image->page.y=0;
952 blob = rotated_image->blob;
953 rotated_image->blob = image->blob;
954 rotated_image->colors = image->colors;
956 AppendImageToList(&image,rotated_image);
957 DeleteImageFromList(&image);
965 DeleteImageFromList(&image2);
970 fclose(clone_info->file);
971 clone_info->file = NULL;
972 (void) unlink(clone_info->filename);
977 /* Allocate next image structure. */
978 AcquireNextImage(image_info,image);
979 if (image->next == (Image *) NULL) break;
980 image=SyncNextImageInList(image);
981 image->columns=image->rows=0;
984 /* row scan buffer is no longer needed */
985 RelinquishMagickMemory(BImgBuff);
988 clone_info=DestroyImageInfo(clone_info);
990 RelinquishMagickMemory(BImgBuff);
999 Rewind list, removing any empty images while rewinding.
1003 while (p != (Image *)NULL)
1006 if ((p->rows == 0) || (p->columns == 0)) {
1008 DeleteImageFromList(&tmp);
1018 for (p=image; p != (Image *) NULL; p=p->next)
1022 if(clone_info != NULL) /* cleanup garbage file from compression */
1024 if(clone_info->file)
1026 fclose(clone_info->file);
1027 clone_info->file = NULL;
1028 (void) unlink(clone_info->filename);
1030 DestroyImageInfo(clone_info);
1033 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1035 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1040 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1044 % R e g i s t e r M A T I m a g e %
1048 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1050 % Method RegisterMATImage adds attributes for the MAT image format to
1051 % the list of supported formats. The attributes include the image format
1052 % tag, a method to read and/or write the format, whether the format
1053 % supports the saving of more than one frame to the same file or blob,
1054 % whether the format supports native in-memory I/O, and a brief
1055 % description of the format.
1057 % The format of the RegisterMATImage method is:
1059 % size_t RegisterMATImage(void)
1062 ModuleExport size_t RegisterMATImage(void)
1067 entry=SetMagickInfo("MAT");
1068 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1069 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1070 entry->blob_support=MagickFalse;
1071 entry->seekable_stream=MagickTrue;
1072 entry->description=AcquireString("MATLAB level 5 image format");
1073 entry->module=AcquireString("MAT");
1074 (void) RegisterMagickInfo(entry);
1075 return(MagickImageCoderSignature);
1079 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1083 % U n r e g i s t e r M A T I m a g e %
1087 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1089 % Method UnregisterMATImage removes format registrations made by the
1090 % MAT module from the list of supported formats.
1092 % The format of the UnregisterMATImage method is:
1094 % UnregisterMATImage(void)
1097 ModuleExport void UnregisterMATImage(void)
1099 (void) UnregisterMagickInfo("MAT");
1103 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1107 % W r i t e M A T L A B I m a g e %
1111 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1113 % Function WriteMATImage writes an Matlab matrix to a file.
1115 % The format of the WriteMATImage method is:
1117 % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
1119 % A description of each parameter follows.
1121 % o status: Function WriteMATImage return True if the image is written.
1122 % False is returned is there is a memory shortage or if the image file
1125 % o image_info: Specifies a pointer to a ImageInfo structure.
1127 % o image: A pointer to an Image structure.
1130 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
1137 const PixelPacket *p;
1139 unsigned int status;
1143 char MATLAB_HDR[0x80];
1144 time_t current_time;
1145 struct tm local_time;
1146 unsigned char *pixels;
1156 Open output image file.
1158 assert(image_info != (const ImageInfo *) NULL);
1159 assert(image_info->signature == MagickSignature);
1160 assert(image != (Image *) NULL);
1161 assert(image->signature == MagickSignature);
1162 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1164 status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
1165 if (status == MagickFalse)
1166 return(MagickFalse);
1169 current_time=time((time_t *) NULL);
1170 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1171 (void) localtime_r(¤t_time,&local_time);
1173 (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
1175 (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1176 FormatMagickString(MATLAB_HDR,MaxTextExtent,"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1177 OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1178 local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1179 local_time.tm_sec,local_time.tm_year+1900);
1182 MATLAB_HDR[0x7E]='I';
1183 MATLAB_HDR[0x7F]='M';
1184 (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1188 if (image->colorspace != RGBColorspace)
1189 (void) TransformImageColorspace(image,RGBColorspace);
1191 is_gray = IsGrayImage(image,&image->exception);
1192 z = is_gray ? 0 : 3;
1197 DataSize = image->rows /*Y*/ * image->columns /*X*/;
1198 if(!is_gray) DataSize *= 3 /*Z*/;
1199 padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1201 (void) WriteBlobLSBLong(image, miMATRIX);
1202 (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
1203 (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1204 (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1205 (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
1206 (void) WriteBlobLSBLong(image, 0);
1207 (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1208 (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
1209 (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
1210 (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
1213 (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
1214 (void) WriteBlobLSBLong(image, 0);
1216 (void) WriteBlobLSBShort(image, 1); /* 0xB0 */
1217 (void) WriteBlobLSBShort(image, 1); /* 0xB2 */
1218 (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1219 (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
1220 (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
1225 exception=(&image->exception);
1226 quantum_info=AcquireQuantumInfo(image_info,image);
1227 if (quantum_info == (QuantumInfo *) NULL)
1228 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1229 pixels=GetQuantumPixels(quantum_info);
1232 for (y=0; y < (ssize_t)image->columns; y++)
1234 p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
1235 if (p == (const PixelPacket *) NULL)
1237 (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
1238 z2qtype[z],pixels,exception);
1239 (void) WriteBlob(image,image->rows,pixels);
1241 if (!SyncAuthenticPixels(image,exception))
1244 while(padding-->0) (void) WriteBlobByte(image,0);
1245 quantum_info=DestroyQuantumInfo(quantum_info);
1246 if (GetNextImageInList(image) == (Image *) NULL)
1248 image=SyncNextImageInList(image);
1249 status=SetImageProgress(image,SaveImagesTag,scene++,
1250 GetImageListLength(image));
1251 if (status == MagickFalse)
1253 } while (image_info->adjoin != MagickFalse);
1254 (void) CloseBlob(image);