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 /** This procedure decompreses an image block for a new MATLAB format. */
450 static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
452 #if defined(MAGICKCORE_ZLIB_DELEGATE)
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);
510 if(status == Z_STREAM_END) goto DblBreak;
517 (void)fclose(mat_file);
518 RelinquishMagickMemory(CacheBlock);
519 RelinquishMagickMemory(DecompressBlock);
521 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
522 if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
523 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
524 if (status == MagickFalse)
526 DeleteImageFromList(&image2);
528 fclose(clone_info->file);
529 clone_info->file = NULL;
531 (void) unlink(clone_info->filename);
546 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
550 % R e a d M A T L A B i m a g e %
554 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
556 % ReadMATImage() reads an MAT X image file and returns it. It
557 % allocates the memory necessary for the new Image structure and returns a
558 % pointer to the new image.
560 % The format of the ReadMATImage method is:
562 % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
564 % A description of each parameter follows:
566 % o image: Method ReadMATImage returns a pointer to the image after
567 % reading. A null image is returned if there is a memory shortage or if
568 % the image cannot be read.
570 % o image_info: Specifies a pointer to a ImageInfo structure.
572 % o exception: return any errors or warnings in this structure.
576 static inline size_t MagickMin(const size_t x,const size_t y)
583 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
585 Image *image, *image2=NULL,
590 MATHeader MATLAB_HDR;
593 QuantumInfo *quantum_info;
594 ImageInfo *clone_info;
597 unsigned char *BImgBuff = NULL;
598 double MinVal, MaxVal;
603 MagickOffsetType filepos=0x80;
607 unsigned int (*ReadBlobXXXLong)(Image *image);
608 unsigned short (*ReadBlobXXXShort)(Image *image);
609 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
610 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
613 assert(image_info != (const ImageInfo *) NULL);
614 assert(image_info->signature == MagickSignature);
615 assert(exception != (ExceptionInfo *) NULL);
616 assert(exception->signature == MagickSignature);
617 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
622 image = AcquireImage(image_info);
624 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
625 if (status == MagickFalse)
627 image=DestroyImageList(image);
628 return((Image *) NULL);
633 clone_info=CloneImageInfo(image_info);
634 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
635 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
636 MATLAB_HDR.Version = ReadBlobLSBShort(image);
637 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
638 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
640 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
641 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
642 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
644 ReadBlobXXXLong = ReadBlobLSBLong;
645 ReadBlobXXXShort = ReadBlobLSBShort;
646 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
647 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
648 image->endian = LSBEndian;
650 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
652 ReadBlobXXXLong = ReadBlobMSBLong;
653 ReadBlobXXXShort = ReadBlobMSBShort;
654 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
655 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
656 image->endian = MSBEndian;
659 goto MATLAB_KO; /* unsupported endian */
661 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
662 MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
664 filepos = TellBlob(image);
665 while(!EOFBlob(image)) /* object parser loop */
667 (void) SeekBlob(image,filepos,SEEK_SET);
668 /* printf("pos=%X\n",TellBlob(image)); */
670 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
671 if(EOFBlob(image)) break;
672 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
673 if(EOFBlob(image)) break;
674 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
677 #if defined(MAGICKCORE_ZLIB_DELEGATE)
678 if(MATLAB_HDR.DataType == miCOMPRESSED)
680 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
681 if(image2==NULL) continue;
682 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
686 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
688 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
689 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
691 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
692 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
693 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
695 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
697 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
698 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
699 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
700 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
701 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
704 switch(MATLAB_HDR.DimFlag)
706 case 8: z=1; break; /* 2D matrix*/
707 case 12: z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
708 Unknown6 = ReadBlobXXXLong(image2);
709 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
711 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
714 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
715 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
717 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
718 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
719 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
720 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
721 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
722 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
723 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
724 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
725 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
726 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
727 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
728 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
729 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
730 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
732 switch (MATLAB_HDR.NameFlag)
735 size = ReadBlobXXXLong(image2); /* Object name string size */
736 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
737 (void) SeekBlob(image2, size, SEEK_CUR);
743 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
749 CellType = ReadBlobXXXLong(image2); /* Additional object type */
751 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
752 "MATLAB_HDR.CellType: %.20g",(double) CellType);
754 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
756 /* Image is gray when no complex flag is set and 2D Matrix */
757 if ((MATLAB_HDR.DimFlag == 8) &&
758 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
759 image->type=GrayscaleType;
766 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
769 image->depth = 8; /* Byte type cell */
770 ldblk = (ssize_t) MATLAB_HDR.SizeX;
775 image->depth = 16; /* Word type cell */
776 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
781 image->depth = 32; /* Dword type cell */
782 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
787 image->depth = 64; /* Qword type cell */
788 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
792 image->depth = 32; /* double type cell */
793 (void) SetImageOption(clone_info,"quantum:format","floating-point");
794 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
795 { /* complex float type cell */
797 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
801 image->depth = 64; /* double type cell */
802 (void) SetImageOption(clone_info,"quantum:format","floating-point");
803 if (sizeof(double) != 8)
804 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
805 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
806 { /* complex double type cell */
808 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
811 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
813 image->columns = MATLAB_HDR.SizeX;
814 image->rows = MATLAB_HDR.SizeY;
815 quantum_info=AcquireQuantumInfo(clone_info,image);
816 if (quantum_info == (QuantumInfo *) NULL)
817 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
819 image->colors = one << image->depth;
820 if (image->columns == 0 || image->rows == 0)
823 /* ----- Create gray palette ----- */
825 if (CellType==miUINT8 && z!=3)
827 if(image->colors>256) image->colors = 256;
829 if (!AcquireImageColormap(image, image->colors))
831 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
835 If ping is true, then only set image size and colors without
836 reading any image data.
838 if (image_info->ping)
840 size_t temp = image->columns;
841 image->columns = image->rows;
843 goto done_reading; /* !!!!!! BAD !!!! */
846 /* ----- Load raster data ----- */
847 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
848 if (BImgBuff == NULL)
853 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
855 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
858 /* Main loop for reading all scanlines */
859 if(z==1) z=0; /* read grey scanlines */
860 /* else read color scanlines */
863 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
865 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
866 if (q == (PixelPacket *)NULL)
868 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
869 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
870 goto done_reading; /* Skip image rotation, when cannot set image pixels */
872 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
874 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
875 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
878 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
880 FixLogical((unsigned char *)BImgBuff,ldblk);
881 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
883 ImportQuantumPixelsFailed:
884 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
885 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
891 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
892 goto ImportQuantumPixelsFailed;
895 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
896 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
897 FixSignedValues(q,MATLAB_HDR.SizeX);
900 if (!SyncAuthenticPixels(image,exception))
902 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
903 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
911 /* Read complex part of numbers here */
912 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
913 { /* Find Min and Max Values for complex parts of floats */
914 CellType = ReadBlobXXXLong(image2); /* Additional object type */
915 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
917 if (CellType==miDOUBLE || CellType==miSINGLE)
919 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
922 if (CellType==miDOUBLE)
923 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
925 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
926 InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
929 if (CellType==miSINGLE)
930 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
932 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
933 InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
937 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
938 if ((MATLAB_HDR.DimFlag == 8) &&
939 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
940 image->type=GrayscaleType;
941 if (image->depth == 1)
942 image->type=BilevelType;
945 image2 = NULL; /* Remove shadow copy to an image before rotation. */
948 rotated_image = RotateImage(image, 90.0, exception);
949 if (rotated_image != (Image *) NULL)
951 /* Remove page offsets added by RotateImage */
952 rotated_image->page.x=0;
953 rotated_image->page.y=0;
955 blob = rotated_image->blob;
956 rotated_image->blob = image->blob;
957 rotated_image->colors = image->colors;
959 AppendImageToList(&image,rotated_image);
960 DeleteImageFromList(&image);
968 DeleteImageFromList(&image2);
973 fclose(clone_info->file);
974 clone_info->file = NULL;
975 (void) unlink(clone_info->filename);
980 /* Allocate next image structure. */
981 AcquireNextImage(image_info,image);
982 if (image->next == (Image *) NULL) break;
983 image=SyncNextImageInList(image);
984 image->columns=image->rows=0;
987 /* row scan buffer is no longer needed */
988 RelinquishMagickMemory(BImgBuff);
991 clone_info=DestroyImageInfo(clone_info);
993 RelinquishMagickMemory(BImgBuff);
1002 Rewind list, removing any empty images while rewinding.
1006 while (p != (Image *)NULL)
1009 if ((p->rows == 0) || (p->columns == 0)) {
1011 DeleteImageFromList(&tmp);
1021 for (p=image; p != (Image *) NULL; p=p->next)
1025 if(clone_info != NULL) /* cleanup garbage file from compression */
1027 if(clone_info->file)
1029 fclose(clone_info->file);
1030 clone_info->file = NULL;
1031 (void) unlink(clone_info->filename);
1033 DestroyImageInfo(clone_info);
1036 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1038 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1043 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1047 % R e g i s t e r M A T I m a g e %
1051 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1053 % Method RegisterMATImage adds attributes for the MAT image format to
1054 % the list of supported formats. The attributes include the image format
1055 % tag, a method to read and/or write the format, whether the format
1056 % supports the saving of more than one frame to the same file or blob,
1057 % whether the format supports native in-memory I/O, and a brief
1058 % description of the format.
1060 % The format of the RegisterMATImage method is:
1062 % size_t RegisterMATImage(void)
1065 ModuleExport size_t RegisterMATImage(void)
1070 entry=SetMagickInfo("MAT");
1071 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1072 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1073 entry->blob_support=MagickFalse;
1074 entry->seekable_stream=MagickTrue;
1075 entry->description=AcquireString("MATLAB level 5 image format");
1076 entry->module=AcquireString("MAT");
1077 (void) RegisterMagickInfo(entry);
1078 return(MagickImageCoderSignature);
1082 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1086 % U n r e g i s t e r M A T I m a g e %
1090 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1092 % Method UnregisterMATImage removes format registrations made by the
1093 % MAT module from the list of supported formats.
1095 % The format of the UnregisterMATImage method is:
1097 % UnregisterMATImage(void)
1100 ModuleExport void UnregisterMATImage(void)
1102 (void) UnregisterMagickInfo("MAT");
1106 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1110 % W r i t e M A T L A B I m a g e %
1114 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1116 % Function WriteMATImage writes an Matlab matrix to a file.
1118 % The format of the WriteMATImage method is:
1120 % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
1122 % A description of each parameter follows.
1124 % o status: Function WriteMATImage return True if the image is written.
1125 % False is returned is there is a memory shortage or if the image file
1128 % o image_info: Specifies a pointer to a ImageInfo structure.
1130 % o image: A pointer to an Image structure.
1133 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
1140 const PixelPacket *p;
1142 unsigned int status;
1146 char MATLAB_HDR[0x80];
1147 time_t current_time;
1148 struct tm local_time;
1149 unsigned char *pixels;
1159 Open output image file.
1161 assert(image_info != (const ImageInfo *) NULL);
1162 assert(image_info->signature == MagickSignature);
1163 assert(image != (Image *) NULL);
1164 assert(image->signature == MagickSignature);
1165 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1166 status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
1167 if (status == MagickFalse)
1168 return(MagickFalse);
1171 current_time=time((time_t *) NULL);
1172 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1173 (void) localtime_r(¤t_time,&local_time);
1175 (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
1177 (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1178 FormatMagickString(MATLAB_HDR,MaxTextExtent,"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1179 OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1180 local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1181 local_time.tm_sec,local_time.tm_year+1900);
1184 MATLAB_HDR[0x7E]='I';
1185 MATLAB_HDR[0x7F]='M';
1186 (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1190 if (image->colorspace != RGBColorspace)
1191 (void) TransformImageColorspace(image,RGBColorspace);
1193 is_gray = IsGrayImage(image,&image->exception);
1194 z = is_gray ? 0 : 3;
1199 DataSize = image->rows /*Y*/ * image->columns /*X*/;
1200 if(!is_gray) DataSize *= 3 /*Z*/;
1201 padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1203 (void) WriteBlobLSBLong(image, miMATRIX);
1204 (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
1205 (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1206 (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1207 (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
1208 (void) WriteBlobLSBLong(image, 0);
1209 (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1210 (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
1211 (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
1212 (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
1215 (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
1216 (void) WriteBlobLSBLong(image, 0);
1218 (void) WriteBlobLSBShort(image, 1); /* 0xB0 */
1219 (void) WriteBlobLSBShort(image, 1); /* 0xB2 */
1220 (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1221 (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
1222 (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
1227 exception=(&image->exception);
1228 quantum_info=AcquireQuantumInfo(image_info,image);
1229 if (quantum_info == (QuantumInfo *) NULL)
1230 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1231 pixels=GetQuantumPixels(quantum_info);
1234 for (y=0; y < (ssize_t)image->columns; y++)
1236 p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
1237 if (p == (const PixelPacket *) NULL)
1239 (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
1240 z2qtype[z],pixels,exception);
1241 (void) WriteBlob(image,image->rows,pixels);
1243 if (!SyncAuthenticPixels(image,exception))
1246 while(padding-->0) (void) WriteBlobByte(image,0);
1247 quantum_info=DestroyQuantumInfo(quantum_info);
1248 if (GetNextImageInList(image) == (Image *) NULL)
1250 image=SyncNextImageInList(image);
1251 status=SetImageProgress(image,SaveImagesTag,scene++,
1252 GetImageListLength(image));
1253 if (status == MagickFalse)
1255 } while (image_info->adjoin != MagickFalse);
1256 (void) CloseBlob(image);