分享

Cocos2d-x之CCImage深入分析

 勤奋不止 2013-08-05

                Cocos2d-xCCImage深入分析  

 

      本节所用Cocos2d-x版本:cocos2d-2.0-x-2.0.2

            CCImage类:支持从JPG,PNG,TIFF以及数据流,字符串中创建供Cocos2d-x进行访问的图片数据对象。

        这是一个非常重要的类,因为它是你使用cocos2d-x来加载图片的基础。目前此类只支持JPG,PNG,TIFF三种图像文件,对于这三种图像文件,CCImage分别使用libjpg,libpng,libtiff进行读取访问和写文件的操作。有兴趣的同学可以上网查询相关图像库的分析和使用,同时建议有能力的同学对此类进行扩展,令它支持更多的图像格式,是为“举一反三”。

        学之前最好先了解一下libjpg,libpng,libtiff等图片功能库的使用。可以参见文章底部的参考资料。

       现在,先来看CCImage图像头文件:


  1. #ifndef __CC_IMAGE_H__  
  2. #define __CC_IMAGE_H__  
  3. //派生于CCObject  
  4. #include "cocoa/CCObject.h"  
  5. //Cocos2d命名空间  
  6. NS_CC_BEGIN  
  7.   
  8. class CC_DLL CCImage : public CCObject  
  9. {  
  10. public:  
  11.     //构造函数  
  12.     CCImage();  
  13.     //析构函数  
  14.     ~CCImage();  
  15.     //支持的图片类型  
  16.     typedef enum  
  17.     {     
  18.         kFmtJpg = 0,    //JPG  
  19.         kFmtPng,        //PNG  
  20.         kFmtTiff,       //TIFF  
  21.         kFmtRawData,    //数据流,要求为RGBA8888  
  22.         kFmtUnKnown //无效  
  23.     }EImageFormat;  
  24.     //对齐方式  
  25.     typedef enum  
  26.     {  
  27.         kAlignCenter        = 0x33, //横向纵向都居中.  
  28.         kAlignTop           = 0x13, //横向居中,纵向居上.  
  29.         kAlignTopRight      = 0x12, //横向居右,纵向居上.  
  30.         kAlignRight         = 0x32, //横向居中,纵向居中.  
  31.         kAlignBottomRight   = 0x22, //横向居右,纵向居下.  
  32.         kAlignBottom        = 0x23, //横向居中,纵向居下.  
  33.         kAlignBottomLeft    = 0x21, //横向居左,纵向居下.  
  34.         kAlignLeft          = 0x31, //横向居左,纵向居中.  
  35.         kAlignTopLeft       = 0x11, //横向居左,纵向居上.  
  36.     }ETextAlign;  
  37.   
  38.     //从指定的路径载入一个所支持的格式的图片文件。  
  39.     bool initWithImageFile(const char * strPath, EImageFormat imageType = kFmtPng);  
  40.   
  41.     //从指定的路径载入一个所支持的格式的图片文件,但它是线程安全的,因此可以用在多线程加载图片。  
  42.     bool initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType = kFmtPng);  
  43.   
  44.     //从内存中加载图片数据。  
  45.     //参1:指向图片数据所处内存地址的指针。  
  46.     //参2:图片数据长度  
  47.     //参3:数据对应图片的格式,  
  48.     //参4:数据对应图片的宽度  
  49.     //参5:数据对应图片的高度  
  50.     //参6:每像素的字节位数,即色深。  
  51.     bool initWithImageData(void * pData,   
  52.                            int nDataLen,   
  53.                            EImageFormat eFmt = kFmtUnKnown,  
  54.                            int nWidth = 0,  
  55.                            int nHeight = 0,  
  56.                            int nBitsPerComponent = 8);  
  57.   
  58.     //从字符串创建图片数据。  
  59.     //参1:字符串  
  60.     //参2:要创建的图片宽度,如果填0,则按照字符串的宽度进行设置。  
  61.     //参3:要创建的图片高度,如果填0,则按照字符串的高度进行设置。  
  62.     //参4:文字的对齐方式。  
  63.     //参5:字体名称  
  64.     //参6:字体大小  
  65.     bool initWithString(  
  66.         const char *    pText,   
  67.         int             nWidth = 0,   
  68.         int             nHeight = 0,  
  69.         ETextAlign      eAlignMask = kAlignCenter,  
  70.         const char *    pFontName = 0,  
  71.         int             nSize = 0);  
  72.   
  73.     //取得图像数据地址  
  74.     unsigned char *   getData()               { return m_pData; }  
  75.     //取得图像数据的长度  
  76.     int         getDataLen()            { return m_nWidth * m_nHeight; }  
  77.     //是否有Alpha通道。  
  78.     bool hasAlpha()                     { return m_bHasAlpha; }  
  79.     //是否有Alpha渐变  
  80.     bool isPremultipliedAlpha()         { return m_bPreMulti; }  
  81.   
  82.     //将当前图片数据保存成指定的文件格式。  
  83.     //参1:绝对路径名  
  84.     //参2:是否保存成RGB格式  
  85.     bool saveToFile(const char *pszFilePath, bool bIsToRGB = true);  
  86.     //定义变量m_nWidth和get接口  
  87.     CC_SYNTHESIZE_READONLY(unsigned short,   m_nWidth,       Width);  
  88.     //定义变量m_nHeight和get接口  
  89.     CC_SYNTHESIZE_READONLY(unsigned short,   m_nHeight,      Height);  
  90.     //定义变量m_nBitsPerComponent和get接口  
  91.     CC_SYNTHESIZE_READONLY(int,     m_nBitsPerComponent,   BitsPerComponent);  
  92.   
  93. protected:  
  94.     //读取JPG图片数据  
  95.     //参1:数据地址  
  96.     //参2:数据长度  
  97.     bool _initWithJpgData(void *pData, int nDatalen);  
  98.     //读取PNG图片数据到内存成成Cocos2d-x所用的图像数据保存到m_pData中  
  99.     bool _initWithPngData(void *pData, int nDatalen);  
  100.     //读取TIFF图片数据到内存成成Cocos2d-x所用的图像数据保存到m_pData中  
  101.          bool _initWithTiffData(void* pData, int nDataLen);  
  102.     //读取RGBA8888格式的图片数据。  
  103.     //参1:数据地址  
  104.     //参2:数据长度  
  105.     //参3:图片宽度  
  106.     //参4:图片高度  
  107.     //参5:图片色深  
  108.     bool _initWithRawData(void *pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent);  
  109.     //将图像数据保存为PNG图片  
  110.     bool _saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);  
  111.     //将图像数据保存为JPG图片  
  112.     bool _saveImageToJPG(const char *pszFilePath);  
  113.     //图像数据地址  
  114.     unsigned char *m_pData;  
  115.     //是否有Alpha  
  116.     bool m_bHasAlpha;  
  117.     //是否有Alpha渐变    bool m_bPreMulti;  
  118.   
  119. private:  
  120.     // 拷贝构造与重载等号拷贝  
  121.     CCImage(const CCImage&    rImg);  
  122.     CCImage & operator=(const CCImage&);  
  123. };  
  124.   
  125. NS_CC_END  
  126.   
  127. #endif    // __CC_IMAGE_H__  

继续分析CPP文件,其CPP文件由两个文件构成:

CCImageCommon_cpp.h和CCImage.cpp。在CCImage.cpp的起始代码处:

//定义 基于平台的CCImage的CPP标记宏

#define __CC_PLATFORM_IMAGE_CPP__

//这里引用CCImageCommon_cpp.h

#include "platform/CCImageCommon_cpp.h"

    可以看到这里引用了头文件CCImageCommon_cpp.h。那我们就打开CCImageCommon_cpp.h:

  1. #ifndef __CC_PLATFORM_IMAGE_CPP__  
  2.     //如果没有定义基于平台的CCImage的CPP标记宏,编译时打印出错。  
  3. #error "CCFileUtilsCommon_cpp.h can only be included for CCFileUtils.cpp in platform/win32(android,...)"  
  4. #endif /* __CC_PLATFORM_IMAGE_CPP__ */  
  5.   
  6. #include "CCImage.h"  
  7. #include "CCCommon.h"  
  8. #include "CCStdC.h"  
  9. #include "CCFileUtils.h"  
  10. //libpng库的头文件  
  11. #include "png.h"  
  12. //libjpg库的头文件  
  13. #include "jpeglib.h"  
  14. //libtiff库的头文件  
  15. #include "tiffio.h"  
  16. #include <string>  
  17. #include <ctype.h>  
  18. //使用Cocos2d命名空间  
  19. NS_CC_BEGIN  
  20.   
  21. //定义宏从RGB888或RGB5A1像素格式数据中返回一个RGBA8888的像素格式数据。  
  22. #define CC_RGB_PREMULTIPLY_APLHA(vr, vg, vb, va) \  
  23.     (unsigned)(((unsigned)((unsigned char)(vr) * ((unsigned char)(va) + 1)) >> 8) | \  
  24.     ((unsigned)((unsigned char)(vg) * ((unsigned char)(va) + 1) >> 8) << 8) | \  
  25.     ((unsigned)((unsigned char)(vb) * ((unsigned char)(va) + 1) >> 8) << 16) | \  
  26.     ((unsigned)(unsigned char)(va) << 24))  
  27.   
  28. //图片文件数据的信息结构  
  29. typedef struct   
  30. {  
  31.     unsigned char* data;  
  32.     int size;  
  33.     int offset;  
  34. }tImageSource;  
  35. //读取PNG文件数据的回调函数  
  36. //参1:PNG文件数据指针  
  37. //参2:返回的图片数据地址  
  38. //参3:要从PNG文件中读取的图片数据的长度,其值 = 每像素字节数X图片的宽X图片的高。  
  39. static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)  
  40. {  
  41.     //从一个PNG文件数据指针指针中返回图片文件数据的信息结构  
  42.     tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);  
  43.     //如果要读取的长度有效。则将相应长度的图像数据拷贝到返回的图片数据地址中。  
  44.     if((int)(isource->offset + length) <= isource->size)  
  45.     {  
  46.         memcpy(data, isource->data+isource->offset, length);  
  47.         isource->offset += length;  
  48.     }  
  49.     else  
  50.     {  
  51.         png_error(png_ptr, "pngReaderCallback failed");  
  52.     }  
  53. }  
  54.   
  55. //////////////////////////////////////////////////////////////////////////  
  56. //构造函数  
  57. CCImage::CCImage()  
  58. : m_nWidth(0)  
  59. , m_nHeight(0)  
  60. , m_nBitsPerComponent(0)  
  61. , m_pData(0)  
  62. , m_bHasAlpha(false)  
  63. , m_bPreMulti(false)  
  64. {  
  65.   
  66. }  
  67. //析构函数  
  68. CCImage::~CCImage()  
  69. {     
  70.     //释放图像数据占用的内存  
  71.     CC_SAFE_DELETE_ARRAY(m_pData);  
  72. }  
  73. //从指定的路径载入一个所支持的格式的图片文件。  
  74. bool CCImage::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/)  
  75. {  
  76.     bool bRet = false;  
  77.     unsigned long nSize = 0;  
  78.     //调用文件操作函数库中的函数读取相应路径的文件到内存中,并返回内存的地址给指针变量pBuffer。  
  79.     unsigned char* pBuffer = CCFileUtils::sharedFileUtils()->getFileData(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(strPath), "rb", &nSize);  
  80.     if (pBuffer != NULL && nSize > 0)  
  81.     {     
  82.             //如果读取成功,则将内存地址做为参数调用initWithImageData函数来加载图片数据。  
  83.         bRet = initWithImageData(pBuffer, nSize, eImgFmt);  
  84.     }  
  85.     //释放读取文件所创建的内存。  
  86.     CC_SAFE_DELETE_ARRAY(pBuffer);  
  87.     return bRet;  
  88. }  
  89.   
  90. //从指定的路径载入一个所支持的格式的图片文件,但它是线程安全的,因此可以用在多线程加载图片。  
  91. bool CCImage::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType)  
  92. {  
  93.     bool bRet = false;  
  94.     unsigned long nSize = 0;  
  95.     //调用文件操作函数库中的函数读取相应路径的文件到内存中,并返回内存的地址给指针变量pBuffer。  
  96.     unsigned char *pBuffer = CCFileUtils::sharedFileUtils()->getFileData(fullpath, "rb", &nSize);  
  97.     if (pBuffer != NULL && nSize > 0)  
  98.     {  
  99.     //如果读取成功,则将内存地址做为参数调用initWithImageData函数来加载图片数据。  
  100.         bRet = initWithImageData(pBuffer, nSize, imageType);  
  101.     }  
  102.     //释放读取文件所创建的内存。  
  103.     CC_SAFE_DELETE_ARRAY(pBuffer);  
  104.     return bRet;  
  105. }  
  106.   
  107. //从内存中加载图片数据。  
  108. //参1:指向图片数据所处内存地址的指针。  
  109. //参2:图片数据长度  
  110. //参3:数据对应图片的格式,  
  111. //参4:数据对应图片的宽度  
  112. //参5:数据对应图片的高度  
  113. //参6:每像素的字节位数,即色深。  
  114. bool CCImage::initWithImageData(void * pData,   
  115.                                 int nDataLen,   
  116.                                 EImageFormat eFmt/* = eSrcFmtPng*/,   
  117.                                 int nWidth/* = 0*/,  
  118.                                 int nHeight/* = 0*/,  
  119.                                 int nBitsPerComponent/* = 8*/)  
  120. {  
  121.     bool bRet = false;  
  122.     do   
  123.     {  
  124.             //参数有效性判断  
  125.         CC_BREAK_IF(! pData || nDataLen <= 0);  
  126.         //根据不同的图片数据格式调用不同的函数创建相应的图片数据。  
  127.         if (kFmtPng == eFmt)  
  128.         {     
  129.            //读取PNG格式的图片数据。  
  130.             bRet = _initWithPngData(pData, nDataLen);  
  131.             break;  
  132.         }  
  133.         else if (kFmtJpg == eFmt)  
  134.         {  
  135.             //读取JPG格式的图片数据。  
  136.             bRet = _initWithJpgData(pData, nDataLen);  
  137.             break;  
  138.         }  
  139.         else if (kFmtTiff == eFmt)  
  140.         {  
  141.             //读取TIFF格式的图片数据。  
  142.             bRet = _initWithTiffData(pData, nDataLen);  
  143.             break;  
  144.         }  
  145.         else if (kFmtRawData == eFmt)  
  146.         {  
  147.             //读取RGBA8888格式的图片数据。  
  148.             bRet = _initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent);  
  149.             break;  
  150.         }  
  151.         else  
  152.         {  
  153.             // 如果未指定数据的格式.则通过对比相应格式的文件头信息判断格式。  
  154.            //判断是否是PNG  
  155.             if (nDataLen > 8)  
  156.             {  
  157.                 unsigned char* pHead = (unsigned char*)pData;  
  158.                 if (   pHead[0] == 0x89  
  159.                     && pHead[1] == 0x50  
  160.                     && pHead[2] == 0x4E  
  161.                     && pHead[3] == 0x47  
  162.                     && pHead[4] == 0x0D  
  163.                     && pHead[5] == 0x0A  
  164.                     && pHead[6] == 0x1A  
  165.                     && pHead[7] == 0x0A)  
  166.                 {  
  167.                    //通过对比如果是属于PNG格式则读取PNG格式的图片数据  
  168.                     bRet = _initWithPngData(pData, nDataLen);  
  169.                     break;  
  170.                 }  
  171.             }  
  172.             //判断是否是TIFF  
  173.             if (nDataLen > 2)  
  174.             {  
  175.                 unsigned char* pHead = (unsigned char*)pData;  
  176.                 if (  (pHead[0] == 0x49 && pHead[1] == 0x49)  
  177.                     || (pHead[0] == 0x4d && pHead[1] == 0x4d)  
  178.                     )  
  179.                 {   //通过对比如果是属于TIFF格式则读取TIFF格式的图片数据  
  180.                     bRet = _initWithTiffData(pData, nDataLen);  
  181.                     break;  
  182.                 }  
  183.             }  
  184.             //判断是否是JPG  
  185.             if (nDataLen > 2)  
  186.             {  
  187.                 unsigned char* pHead = (unsigned char*)pData;  
  188.                 if (   pHead[0] == 0xff  
  189.                     && pHead[1] == 0xd8)  
  190.                 {  
  191.                     bRet = _initWithJpgData(pData, nDataLen);  
  192.                     break;  
  193.                 }  
  194.             }  
  195.         }  
  196.     } while (0);  
  197.     return bRet;  
  198. }  
  199. //读取JPG格式的图片数据。  
  200. bool CCImage::_initWithJpgData(void * data, int nSize)  
  201. {  
  202.     //此处使用libjpeg库来读取JPG,这里需要建立相应的结构变量。  
  203.     struct jpeg_decompress_struct cinfo;  
  204.     struct jpeg_error_mgr jerr;  
  205.     JSAMPROW row_pointer[1] = {0};  
  206.     unsigned long location = 0;  
  207.     unsigned int i = 0;  
  208.   
  209.     bool bRet = false;  
  210.     do   
  211.     {  
  212.         //下面是使用libjpeg来进行JPG格式数据的读取。  
  213.   
  214.         cinfo.err = jpeg_std_error( &jerr );  
  215.         jpeg_create_decompress( &cinfo );  
  216.         jpeg_mem_src( &cinfo, (unsigned char *) data, nSize );  
  217.         jpeg_read_header( &cinfo, true );  
  218.   
  219.         // JPG只能支持RGB的像素格式  
  220.         if (cinfo.jpeg_color_space != JCS_RGB)  
  221.         {  
  222.             if (cinfo.jpeg_color_space == JCS_GRAYSCALE || cinfo.jpeg_color_space == JCS_YCbCr)  
  223.             {  
  224.                 cinfo.out_color_space = JCS_RGB;  
  225.             }  
  226.         }  
  227.         else  
  228.         {  
  229.             break;  
  230.         }  
  231.         //开始解压JPG。  
  232.         jpeg_start_decompress( &cinfo );  
  233.   
  234.         //设置相应成员变量。  
  235.         m_nWidth  = (short)(cinfo.image_width);  
  236.         m_nHeight = (short)(cinfo.image_height);  
  237.         m_bHasAlpha = false;  
  238.         m_bPreMulti = false;  
  239.         m_nBitsPerComponent = 8;  
  240.         row_pointer[0] = new unsigned char[cinfo.output_width*cinfo.output_components];  
  241.         CC_BREAK_IF(! row_pointer[0]);  
  242.        //为图片数据指针申请相应大小的内存。  
  243.         m_pData = new unsigned char[cinfo.output_width*cinfo.output_height*cinfo.output_components];  
  244.         CC_BREAK_IF(! m_pData);  
  245.   
  246.       //将像素信息读取到图片数据指针指向的内存中。  
  247.         while( cinfo.output_scanline < cinfo.image_height )  
  248.         {  
  249.            //每次读取一个扫描行的像素信息  
  250.             jpeg_read_scanlines( &cinfo, row_pointer, 1 );  
  251.             for( i=0; i<cinfo.image_width*cinfo.output_components;i++)   
  252.             {  
  253.                //将读取到的像素信息存入相应的内存中。  
  254.                 m_pData[location++] = row_pointer[0][i];  
  255.             }  
  256.         }  
  257.         //完成解压  
  258.         jpeg_finish_decompress( &cinfo );  
  259.         //释放所用的结构  
  260.         jpeg_destroy_decompress( &cinfo );        
  261.         bRet = true;  
  262.     } while (0);  
  263.     //释放申请的内存  
  264.     CC_SAFE_DELETE_ARRAY(row_pointer[0]);  
  265.     return bRet;  
  266. }  
  267. //读取PNG格式的图片数据。  
  268. bool CCImage::_initWithPngData(void * pData, int nDatalen)  
  269. {  
  270. // PNG文件头信息长度值  
  271. #define PNGSIGSIZE  8  
  272.     bool bRet = false;  
  273.     //定义存储PNG文件头信息的BYTE数组  
  274.     png_byte        header[PNGSIGSIZE]   = {0};       
  275.     //PNG的读取说明结构,这里是libpng用到的结构体。  
  276.     png_structp     png_ptr     =   0;  
  277.     //PNG的信息结构  
  278.     png_infop       info_ptr    = 0;  
  279.       
  280.     do   
  281.     {  
  282.         // PNG文件头有效性判断  
  283.         CC_BREAK_IF(nDatalen < PNGSIGSIZE);  
  284.   
  285.         // 存储文件头信息  
  286.         memcpy(header, pData, PNGSIGSIZE);  
  287.         CC_BREAK_IF(png_sig_cmp(header, 0, PNGSIGSIZE));  
  288.   
  289.         //初始化PNG的读取说明结构  
  290.         png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);  
  291.         CC_BREAK_IF(! png_ptr);  
  292.   
  293.         // 初始化 PNG信息结构  
  294.         info_ptr = png_create_info_struct(png_ptr);  
  295.         CC_BREAK_IF(!info_ptr);  
  296.   
  297. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)  
  298.         CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));  
  299. #endif  
  300.   
  301.         //图片文件数据的信息结构  
  302.         tImageSource imageSource;  
  303.         imageSource.data    = (unsigned char*)pData;  
  304.         imageSource.size    = nDatalen;  
  305.         imageSource.offset  = 0;  
  306.        //设置读取PNG的回调函数  
  307.         png_set_read_fn(png_ptr, &imageSource, pngReadCallback);  
  308.   
  309.         //读取PNG信息结构  
  310.         png_read_info(png_ptr, info_ptr);  
  311.         //取得图片数据的相关属性。  
  312.         m_nWidth = png_get_image_width(png_ptr, info_ptr);  
  313.         m_nHeight = png_get_image_height(png_ptr, info_ptr);  
  314.         m_nBitsPerComponent = png_get_bit_depth(png_ptr, info_ptr);  
  315.         png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);  
  316.         //打印像素格式  
  317.         //CCLOG("color type %u", color_type);  
  318.           
  319.         // 如果是调色板格式的PNG,将其转为RGB888的像素格式。  
  320.         if (color_type == PNG_COLOR_TYPE_PALETTE)  
  321.         {  
  322.             png_set_palette_to_rgb(png_ptr);  
  323.         }  
  324.         // 如果是像素格式少于1字节长度的灰度图,将其转为每像素占1字节的像素格式。  
  325.         if (color_type == PNG_COLOR_TYPE_GRAY && m_nBitsPerComponent < 8)  
  326.         {  
  327.             png_set_expand_gray_1_2_4_to_8(png_ptr);  
  328.         }  
  329.         // 将RNS块数据信息扩展为完整的ALPHA通道信息  
  330.         if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))  
  331.         {  
  332.             png_set_tRNS_to_alpha(png_ptr);  
  333.         }    
  334.         // reduce images with 16-bit samples to 8 bits  
  335.         if (m_nBitsPerComponent == 16)  
  336.         {  
  337.             png_set_strip_16(png_ptr);              
  338.         }   
  339.         // 将灰度图格式扩展成RGB  
  340.         if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)  
  341.         {  
  342.             png_set_gray_to_rgb(png_ptr);  
  343.         }  
  344.   
  345.         // 读取PNG数据  
  346.         // m_nBitsPerComponent will always be 8  
  347.         m_nBitsPerComponent = 8;  
  348.         png_uint_32 rowbytes;  
  349.        //后面读取PNG信息是按行读取,将每一行的像素数据读取到相应内存块中,下面这个BYTE指针数组就是为了存储每行图片像素信息读取到的相应内存块位置。  
  350.         png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * m_nHeight );  
  351.           
  352.         png_read_update_info(png_ptr, info_ptr);  
  353.         //取得图片每一行像素的字节数量  
  354.         rowbytes = png_get_rowbytes(png_ptr, info_ptr);  
  355.         //为图片数据申请内存。  
  356.         m_pData = new unsigned char[rowbytes * m_nHeight];  
  357.         CC_BREAK_IF(!m_pData);  
  358.         //将申请到的内存地址按行放入相应的读取结构中  
  359.         for (unsigned short i = 0; i < m_nHeight; ++i)  
  360.         {  
  361.             row_pointers[i] = m_pData + i*rowbytes;  
  362.         }  
  363.         //将图片文件数据读取到相应的内存地址。  
  364.         png_read_image(png_ptr, row_pointers);  
  365.         //结束读取。  
  366.         png_read_end(png_ptr, NULL);  
  367.         //计算每像素占字节数。不管是RGB888还是RGBA8888的像素格式,其实际每像素占用的字节数均是4,只不过RGB888中多余的1字节不被用到。  
  368.         png_uint_32 channel = rowbytes/m_nWidth;  
  369.         if (channel == 4)  
  370.         {  
  371.            //设置为带ALPHA通道  
  372.             m_bHasAlpha = true;  
  373.            //定义指针变量tmp指向图像数据地址。用于在后面存放图像数据。  
  374.             unsigned int *tmp = (unsigned int *)m_pData;  
  375.            //双循环遍历像素数据。  
  376.             for(unsigned short i = 0; i < m_nHeight; i++)  
  377.             {  
  378.                 for(unsigned int j = 0; j < rowbytes; j += 4)  
  379.                 {  
  380.                    //将R,G,B,A四个BYTE值组成一个DWORD值。  
  381.                     *tmp++ = CC_RGB_PREMULTIPLY_APLHA( row_pointers[i][j], row_pointers[i][j + 1],   
  382.                                                       row_pointers[i][j + 2], row_pointers[i][j + 3] );  
  383.                 }  
  384.             }  
  385.             //设置使用渐变ALPHA  
  386.             m_bPreMulti = true;  
  387.         }  
  388.        //释放row_pointers  
  389.         CC_SAFE_FREE(row_pointers);  
  390.   
  391.         bRet = true;  
  392.     } while (0);  
  393.   
  394.     if (png_ptr)  
  395.     {  
  396.             //释放png_ptr  
  397.         png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);  
  398.     }  
  399.     return bRet;  
  400. }  
  401. //读取TIFF图片数据时的回调函数。  
  402. //参1:文件数据内存。  
  403. //参2:输出参数,读取到的图像数据复制到对应的内存地址中。  
  404. //参3:图片数据长度。  
  405. static tmsize_t _tiffReadProc(thandle_t fd, void* buf, tmsize_t size)  
  406. {  
  407.     //将fd转化为图片文件数据的信息结构指针。  
  408.     tImageSource* isource = (tImageSource*)fd;  
  409.     uint8* ma;  
  410.     uint64 mb;  
  411.     //定义一次可以读取的数据长度。  
  412.     unsigned long n;  
  413.     //定义变量o统计每次循环读取的数据长度。  
  414.     unsigned long o;  
  415.     //定义变量统计读取完的数据长度。  
  416.     tmsize_t p;  
  417.     //让前面定义的uint8类型指针变量ma指向buf。用于在后面存放图像数据。  
  418.     ma=(uint8*)buf;  
  419.     //让前面定义的变量mb来统计剩余未读取的数据长度。  
  420.     mb=size;  
  421.     p=0;  
  422.     //使用while循环进行读取,判断条件为剩余未读的数据长度是否大于0。  
  423.     while (mb>0)  
  424.     {  
  425.         n=0x80000000UL;  
  426.         if ((uint64)n>mb)  
  427.             n=(unsigned long)mb;  
  428.   
  429.         //如果尚未读完所有数据,则继续读取,否则出错返回0  
  430.         if((int)(isource->offset + n) <= isource->size)  
  431.         {  
  432.             memcpy(ma, isource->data+isource->offset, n);  
  433.             isource->offset += n;  
  434.             o = n;  
  435.         }  
  436.         else  
  437.         {  
  438.             return 0;  
  439.         }  
  440.         //读取完长度为o的数据,则对指针进行相应的偏移操作供下次进行读取操作。  
  441.         ma+=o;  
  442.        //更新未读取的剩余长度  
  443.         mb-=o;  
  444.        //更新读取完的数量长度  
  445.         p+=o;  
  446.         //下面这个if比较奇怪,因为是不可能为true的。在上一个if判断中已经设置了o=n。  
  447.         if (o!=n)  
  448.         {  
  449.             break;  
  450.         }  
  451.     }  
  452.     return p;  
  453. }  
  454. //将数据保存为tiff图像文件所调用的回调函数。这里未用。  
  455. static tmsize_t _tiffWriteProc(thandle_t fd, void* buf, tmsize_t size)  
  456. {  
  457.     CC_UNUSED_PARAM(fd);  
  458.     CC_UNUSED_PARAM(buf);  
  459.     CC_UNUSED_PARAM(size);  
  460.     return 0;  
  461. }  
  462.   
  463. //在对TIFF图像文件进行解析时进行重定位时调用的回调函数。  
  464. static uint64 _tiffSeekProc(thandle_t fd, uint64 off, int whence)  
  465. {  
  466.     //将fd转化为图片文件数据的信息结构指针。  
  467.     tImageSource* isource = (tImageSource*)fd;  
  468.     uint64 ret = -1;  
  469.     do   
  470.     {  
  471.            //如果定位方式为从头开始计算  
  472.         if (whence == SEEK_SET)  
  473.         {  
  474.             CC_BREAK_IF(off > isource->size-1);  
  475.             ret = isource->offset = (uint32)off;  
  476.         }  
  477.         else if (whence == SEEK_CUR)  
  478.         {  //如果定位方式为从当前位置开始计算  
  479.             CC_BREAK_IF(isource->offset + off > isource->size-1);  
  480.             ret = isource->offset += (uint32)off;  
  481.         }  
  482.         else if (whence == SEEK_END)  
  483.         {   //如果定位方工业从文件尾部开始计算  
  484.             CC_BREAK_IF(off > isource->size-1);  
  485.             ret = isource->offset = (uint32)(isource->size-1 - off);  
  486.         }  
  487.         else  
  488.         {//其它方式也按照从头开始计算  
  489.             CC_BREAK_IF(off > isource->size-1);  
  490.             ret = isource->offset = (uint32)off;  
  491.         }  
  492.     } while (0);  
  493.   
  494.     return ret;  
  495. }  
  496. //取得tiff图片文件大小的回调函数。  
  497. static uint64 _tiffSizeProc(thandle_t fd)  
  498. {  
  499.     tImageSource* pImageSrc = (tImageSource*)fd;  
  500.     return pImageSrc->size;  
  501. }  
  502. //关闭tiff图片文件读取的回调函数。  
  503. static int _tiffCloseProc(thandle_t fd)  
  504. {  
  505.     CC_UNUSED_PARAM(fd);  
  506.     return 0;  
  507. }  
  508. //将tiff图片文件映射到内存时调用的回调函数。  
  509. static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize)  
  510. {  
  511.     CC_UNUSED_PARAM(fd);  
  512.     CC_UNUSED_PARAM(pbase);  
  513.     CC_UNUSED_PARAM(psize);  
  514.     return 0;  
  515. }  
  516. //解除tiff图片映射到内存的回调函数。  
  517. static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size)  
  518. {  
  519.     CC_UNUSED_PARAM(fd);  
  520.     CC_UNUSED_PARAM(base);  
  521.     CC_UNUSED_PARAM(size);  
  522. }  
  523. //使用LibTiff读取TIFF格式的图片数据。  
  524. bool CCImage::_initWithTiffData(void* pData, int nDataLen)  
  525. {  
  526.     bool bRet = false;  
  527.     do   
  528.     {  
  529.         //设置图片文件数据的信息结构  
  530.         tImageSource imageSource;  
  531.         imageSource.data    = (unsigned char*)pData;  
  532.         imageSource.size    = nDataLen;  
  533.         imageSource.offset  = 0;  
  534.         //使用libtiff打开一个tif文件,设置对其进行操作的各行为的回调函数。如果成功打开文件返回一个TIFF结构指针。  
  535.         TIFF* tif = TIFFClientOpen("file.tif""r", (thandle_t)&imageSource,   
  536.             _tiffReadProc, _tiffWriteProc,  
  537.             _tiffSeekProc, _tiffCloseProc, _tiffSizeProc,  
  538.             _tiffMapProc,  
  539.             _tiffUnmapProc);  
  540.         //有效性判断。  
  541.         CC_BREAK_IF(NULL == tif);  
  542.           
  543.         uint32 w = 0, h = 0;  
  544.         uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0;  
  545.        //定义变量nPixels存储图像数据像素数量。  
  546.         size_t npixels = 0;  
  547.         //读取相应的图片属性信息。  
  548.         //图片宽度。  
  549.         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);  
  550.         //图片高度。  
  551.         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);  
  552.         //图片色深。  
  553.         TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);  
  554.         //每像素数据占的字节数  
  555.         TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);  
  556.         //图像的平面配置  
  557.         TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig);  
  558.         //取得像素数量  
  559.         npixels = w * h;  
  560.         //设置带ALPHA通道。  
  561.         m_bHasAlpha = true;  
  562.         m_nWidth = w;  
  563.         m_nHeight = h;  
  564.         m_nBitsPerComponent = 8;  
  565.        //申请相应的内存用来存储像素数据。  
  566.         m_pData = new unsigned char[npixels * sizeof (uint32)];  
  567.        //申请临时内存进行TIFF数据读取。  
  568.         uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));  
  569.         if (raster != NULL)   
  570.         {  
  571.           //读取TIFF数据  
  572.            if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0))  
  573.            {  
  574.                //下面是从TIFF数据中解析生成我们Cocos2d-x所用的图像数据。  
  575.               //这里定义指针变量指向TIFF数据  
  576.                 unsigned char* src = (unsigned char*)raster;  
  577.               //这里定义指针变量指向我们Cocos2d-x所用的图像数据  
  578.                 unsigned int* tmp = (unsigned int*)m_pData;  
  579.   
  580.     /* 
  581.                 //遍历每像素进行,对像素的RGBA值进行组合,将组合成的DWORD值写入到图像数据中。 
  582.                 for(int j = 0; j < m_nWidth * m_nHeight * 4; j += 4) 
  583.                 { 
  584.                     *tmp++ = CC_RGB_PREMULTIPLY_APLHA( src[j], src[j + 1],  
  585.                         src[j + 2], src[j + 3] ); 
  586.                 } 
  587.     */  
  588.     //ALPHA通道有效。  
  589.                 m_bPreMulti = true;  
  590.               //上面循环将组合后的DWORD值写入图像数据太慢,这里直接进行内存拷贝可以达到同样目的。  
  591.                memcpy(m_pData, raster, npixels*sizeof (uint32));  
  592.            }  
  593.           //释放临时申请的内存。  
  594.           _TIFFfree(raster);  
  595.         }  
  596.           
  597.   
  598.         //关闭TIFF文件读取。  
  599.         TIFFClose(tif);  
  600.   
  601.         bRet = true;  
  602.     } while (0);  
  603.     return bRet;  
  604. }  
  605. //读取RGBA8888格式的图片数据。  
  606. //参1:数据地址  
  607. //参2:数据长度  
  608. //参3:图片宽度  
  609. //参4:图片高度  
  610. //参5:图片色深  
  611. bool CCImage::_initWithRawData(void * pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent)  
  612. {  
  613.     bool bRet = false;  
  614.     do   
  615.     {  
  616.        //宽高有效性判断  
  617.         CC_BREAK_IF(0 == nWidth || 0 == nHeight);  
  618.        //保存相关属性  
  619.         m_nBitsPerComponent = nBitsPerComponent;  
  620.         m_nHeight   = (short)nHeight;  
  621.         m_nWidth    = (short)nWidth;  
  622.         m_bHasAlpha = true;  
  623.   
  624.         // 只支持 RGBA8888 格式  
  625.         int nBytesPerComponent = 4;  
  626.         int nSize = nHeight * nWidth * nBytesPerComponent;  
  627.         //为图像数据申请相应内存,将地址返回给m_pData。   
  628.         m_pData = new unsigned char[nSize];  
  629.         //内存申请成败判断  
  630.         CC_BREAK_IF(! m_pData);  
  631.        //将参数数据拷贝到m_pData指向的内存地址中。  
  632.         memcpy(m_pData, pData, nSize);  
  633.   
  634.         bRet = true;  
  635.     } while (0);  
  636.     return bRet;  
  637. }  
  638. //将图像数据保存为图片文件,目前只支持PNG和JPG  
  639. //参1:文件路径  
  640. //参2:是否是RGB的像素格式  
  641. bool CCImage::saveToFile(const char *pszFilePath, bool bIsToRGB)  
  642. {  
  643.     bool bRet = false;  
  644.   
  645.     do   
  646.     {  
  647.        //参数有效性判断  
  648.         CC_BREAK_IF(NULL == pszFilePath);  
  649.        //通过是否有扩展名判断参数有效性。  
  650.         std::string strFilePath(pszFilePath);  
  651.         CC_BREAK_IF(strFilePath.size() <= 4);  
  652.        //将路径名转为小写字符串  
  653.         std::string strLowerCasePath(strFilePath);  
  654.         for (unsigned int i = 0; i < strLowerCasePath.length(); ++i)  
  655.         {  
  656.             strLowerCasePath[i] = tolower(strFilePath[i]);  
  657.         }  
  658.         //通过扩展名转成相应的图片文件  
  659.         //PNG  
  660.         if (std::string::npos != strLowerCasePath.find(".png"))  
  661.         {  
  662.             CC_BREAK_IF(!_saveImageToPNG(pszFilePath, bIsToRGB));  
  663.         }  
  664.         //JPG  
  665.         else if (std::string::npos != strLowerCasePath.find(".jpg"))  
  666.         {  
  667.             CC_BREAK_IF(!_saveImageToJPG(pszFilePath));  
  668.         }  
  669.         else  
  670.         {  
  671.            //不支持其它格式  
  672.             break;  
  673.         }  
  674.   
  675.         bRet = true;  
  676.     } while (0);  
  677.   
  678.     return bRet;  
  679. }  
  680. //将图像数据保存为PNG图片  
  681. bool CCImage::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB)  
  682. {  
  683.     bool bRet = false;  
  684.     do   
  685.     {  
  686.         //参数有效性判断  
  687.         CC_BREAK_IF(NULL == pszFilePath);  
  688.        //使用libpng来写PNG文件。  
  689.        //定义文件指针变量用于写文件  
  690.         FILE *fp;  
  691.        //定义libpng所用的一些信息结构  
  692.         png_structp png_ptr;  
  693.         png_infop info_ptr;  
  694.         png_colorp palette;  
  695.         png_bytep *row_pointers;  
  696.        //打开文件开始写入  
  697.         fp = fopen(pszFilePath, "wb");  
  698.         CC_BREAK_IF(NULL == fp);  
  699.        //创建写PNG的文件结构体,将其结构指针返回给png_ptr  
  700.         png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);  
  701.        //指针有效性判断  
  702.         if (NULL == png_ptr)  
  703.         {  
  704.             fclose(fp);  
  705.             break;  
  706.         }  
  707.        //创建PNG的信息结构体,将其结构指针返回给info_ptr。  
  708.         info_ptr = png_create_info_struct(png_ptr);  
  709.         if (NULL == info_ptr)  
  710.         {  
  711.             fclose(fp);  
  712.             png_destroy_write_struct(&png_ptr, NULL);  
  713.             break;  
  714.         }  
  715. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)  
  716.         if (setjmp(png_jmpbuf(png_ptr)))  
  717.         {  
  718.             fclose(fp);  
  719.             png_destroy_write_struct(&png_ptr, &info_ptr);  
  720.             break;  
  721.         }  
  722. #endif  
  723.         //初始化png_ptr  
  724.         png_init_io(png_ptr, fp);  
  725.         //根据是否有ALPHA来写入相应的头信息  
  726.         if (!bIsToRGB && m_bHasAlpha)  
  727.         {  
  728.             png_set_IHDR(png_ptr, info_ptr, m_nWidth, m_nHeight, 8, PNG_COLOR_TYPE_RGB_ALPHA,  
  729.                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);  
  730.         }   
  731.         else  
  732.         {  
  733.             png_set_IHDR(png_ptr, info_ptr, m_nWidth, m_nHeight, 8, PNG_COLOR_TYPE_RGB,  
  734.                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);  
  735.         }  
  736.         //创建调色板  
  737.         palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));  
  738.        //设置调色板  
  739.         png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);  
  740.         //写入info_ptr  
  741.         png_write_info(png_ptr, info_ptr);  
  742.         //  
  743.         png_set_packing(png_ptr);  
  744.         //申请临时存储m_pData中每一行像素数据地址的内存空间,将申请到的内存地址返回给row_pointers。  
  745.         row_pointers = (png_bytep *)malloc(m_nHeight * sizeof(png_bytep));  
  746.         if(row_pointers == NULL)  
  747.         {  
  748.             fclose(fp);  
  749.             png_destroy_write_struct(&png_ptr, &info_ptr);  
  750.             break;  
  751.         }  
  752.         //根据是否有ALPHA分别处理写入像素数据到文件中。  
  753.         if (!m_bHasAlpha)  
  754.         {  
  755.            //如果没有ALPHA,只是RGB,这里将m_pData中数据,遍历每一行,将每一行的起始内存地址放入row_pointers指针数组中。  
  756.             for (int i = 0; i < (int)m_nHeight; i++)  
  757.             {  
  758.                 row_pointers[i] = (png_bytep)m_pData + i * m_nWidth * 3;  
  759.             }  
  760.            //将row_pointers中指向的每一行数据写入文件。  
  761.             png_write_image(png_ptr, row_pointers);  
  762.   
  763.             //释放内存  
  764.     free(row_pointers);  
  765.             row_pointers = NULL;  
  766.         }  
  767.         else  
  768.         {  
  769.            //如果带ALPHA通道。对是否是RGB格式又进行分别处理。  
  770.            //如果是RGB888格式  
  771.             if (bIsToRGB)  
  772.             {  
  773.                //创建临时的内存存放像素数据。每个像素3字节,分别存R,G,B值。  
  774.                 unsigned char *pTempData = new unsigned char[m_nWidth * m_nHeight * 3];  
  775.                 if (NULL == pTempData)  
  776.                 {  
  777.                     fclose(fp);  
  778.                     png_destroy_write_struct(&png_ptr, &info_ptr);  
  779.                     break;  
  780.                 }  
  781.               //双循环遍历每个像素,将R,G,B值保存到数组中。  
  782.                 for (int i = 0; i < m_nHeight; ++i)  
  783.                 {  
  784.                     for (int j = 0; j < m_nWidth; ++j)  
  785.                     {  
  786.                         pTempData[(i * m_nWidth + j) * 3] = m_pData[(i * m_nWidth + j) * 4];  
  787.                         pTempData[(i * m_nWidth + j) * 3 + 1] = m_pData[(i * m_nWidth + j) * 4 + 1];  
  788.                         pTempData[(i * m_nWidth + j) * 3 + 2] = m_pData[(i * m_nWidth + j) * 4 + 2];  
  789.                     }  
  790.                 }  
  791.               //将数组中保存的每行像素的内存地址存入row_pointers数组中。  
  792.                 for (int i = 0; i < (int)m_nHeight; i++)  
  793.                 {  
  794.                     row_pointers[i] = (png_bytep)pTempData + i * m_nWidth * 3;  
  795.                 }  
  796.               //将row_pointers中指向的每一行数据写入文件。  
  797.                 png_write_image(png_ptr, row_pointers);  
  798.                   //释放内存  
  799.                 free(row_pointers);  
  800.                 row_pointers = NULL;  
  801.                  
  802.                 CC_SAFE_DELETE_ARRAY(pTempData);  
  803.             }   
  804.             else  
  805.             {  
  806.                //如果是RGBA8888格式  
  807.                //将数组中保存的每行像素的内存地址存入row_pointers数组中。  
  808.                 for (int i = 0; i < (int)m_nHeight; i++)  
  809.                 {  
  810.                     row_pointers[i] = (png_bytep)m_pData + i * m_nWidth * 4;  
  811.                 }  
  812.                 //将row_pointers中指向的每一行数据写入文件。  
  813.                 png_write_image(png_ptr, row_pointers);  
  814.                //释放内存  
  815.   
  816.                 free(row_pointers);  
  817.                 row_pointers = NULL;  
  818.             }  
  819.         }  
  820.         //结束写PNG文件  
  821.         png_write_end(png_ptr, info_ptr);  
  822.         //释放相应的信息结构  
  823.         png_free(png_ptr, palette);  
  824.         palette = NULL;  
  825.         png_destroy_write_struct(&png_ptr, &info_ptr);  
  826.   
  827.         fclose(fp);  
  828.   
  829.         bRet = true;  
  830.     } while (0);  
  831.     return bRet;  
  832. }  
  833.   
  834. //将图像数据保存为JPG文件  
  835. bool CCImage::_saveImageToJPG(const char * pszFilePath)  
  836. {  
  837.     bool bRet = false;  
  838.     do   
  839.     {  
  840.         //参数有效性判断  
  841.         CC_BREAK_IF(NULL == pszFilePath);  
  842.         //使用libjpg库要用到的相关结构。  
  843.         struct jpeg_compress_struct cinfo;  
  844.         struct jpeg_error_mgr jerr;  
  845.         FILE * outfile;                 /* target file */  
  846.         JSAMPROW row_pointer[1];        /* pointer to JSAMPLE row[s] */  
  847.         int     row_stride;          /* physical row width in image buffer */  
  848.         //初始化相关结构  
  849.         cinfo.err = jpeg_std_error(&jerr);  
  850.         jpeg_create_compress(&cinfo);  
  851.         //开始写入文件  
  852.         CC_BREAK_IF((outfile = fopen(pszFilePath, "wb")) == NULL);  
  853.             //写入JPG头文件基本信息  
  854.         jpeg_stdio_dest(&cinfo, outfile);  
  855.         //填充JPG图像的属性信息结构  
  856.         cinfo.image_width = m_nWidth;         
  857.         cinfo.image_height = m_nHeight;  
  858.         cinfo.input_components = 3;           
  859.         cinfo.in_color_space = JCS_RGB;       
  860.         //将信息结构来设置JPG图像  
  861.         jpeg_set_defaults(&cinfo);  
  862.         //开始进行数据压缩输出  
  863.         jpeg_start_compress(&cinfo, TRUE);  
  864.         //设置每行的字节长度  
  865.         row_stride = m_nWidth * 3;  
  866.         //跟据图像数据是否有ALPHA通道来进行分别处理  
  867.         if (m_bHasAlpha)  
  868.         {  
  869.            //创建内存来存放图像的像素数据。  
  870.             unsigned char *pTempData = new unsigned char[m_nWidth * m_nHeight * 3];  
  871.             if (NULL == pTempData)  
  872.             {  
  873.                 jpeg_finish_compress(&cinfo);  
  874.                 jpeg_destroy_compress(&cinfo);  
  875.                 fclose(outfile);  
  876.                 break;  
  877.             }  
  878.             //双循环遍历每一个图像像素的数据,取R,G,B值存放到临时申请的内存地址中,A值弃之不取。  
  879.             for (int i = 0; i < m_nHeight; ++i)  
  880.             {  
  881.                 for (int j = 0; j < m_nWidth; ++j)  
  882.   
  883.                 {  
  884.                   //因图像数据有A通道,所以找相应的像素地址时会由像素索引x4。  
  885.                     pTempData[(i * m_nWidth + j) * 3] = m_pData[(i * m_nWidth + j) * 4];  
  886.                     pTempData[(i * m_nWidth + j) * 3 + 1] = m_pData[(i * m_nWidth + j) * 4 + 1];  
  887.                     pTempData[(i * m_nWidth + j) * 3 + 2] = m_pData[(i * m_nWidth + j) * 4 + 2];  
  888.                 }  
  889.             }  
  890.            //将扫描行的数据写入JPG文件  
  891.             while (cinfo.next_scanline < cinfo.image_height) {  
  892.                 row_pointer[0] = & pTempData[cinfo.next_scanline * row_stride];  
  893.                 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);  
  894.             }  
  895.   
  896.             CC_SAFE_DELETE_ARRAY(pTempData);  
  897.         }   
  898.         else  
  899.         { //将扫描行的数据写入JPG文件  
  900.             while (cinfo.next_scanline < cinfo.image_height) {  
  901.                 row_pointer[0] = & m_pData[cinfo.next_scanline * row_stride];  
  902.                 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);  
  903.             }  
  904.         }  
  905.         //结束数据压缩,关闭文件并释放相应信息结构。  
  906.         jpeg_finish_compress(&cinfo);  
  907.         fclose(outfile);  
  908.         jpeg_destroy_compress(&cinfo);  
  909.           
  910.         bRet = true;  
  911.     } while (0);  
  912.     return bRet;  
  913. }  
  914.   
  915. NS_CC_END  

现在我们回到CCImage.cpp:


  1. #define __CC_PLATFORM_IMAGE_CPP__  
  2. #include "platform/CCImageCommon_cpp.h"  
  3.   
  4. NS_CC_BEGIN  
  5.   
  6. //此处定义一个BitmapDC类在位图上进行文字绘制。  
  7. class BitmapDC  
  8. {  
  9. public:  
  10.     //构造函数  
  11.     BitmapDC(HWND hWnd = NULL)  
  12.     : m_hDC(NULL)  
  13.     , m_hBmp(NULL)  
  14.     , m_hFont((HFONT)GetStockObject(DEFAULT_GUI_FONT))  
  15.     , m_hWnd(NULL)  
  16.     {  
  17.     //保存窗口句柄  
  18.         m_hWnd = hWnd;  
  19.         //取得窗口的hdc  
  20.         HDC hdc = GetDC(hWnd);  
  21.         //创建兼容的hdc  
  22.         m_hDC   = CreateCompatibleDC(hdc);  
  23.         //释放hdc  
  24.         ReleaseDC(hWnd, hdc);  
  25.     }  
  26.     //析构函数  
  27.     ~BitmapDC()  
  28.     {  
  29.         prepareBitmap(0, 0);  
  30.         if (m_hDC)  
  31.         {  
  32.             DeleteDC(m_hDC);  
  33.         }  
  34.         //创建字体  
  35.         HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);  
  36.         if (hDefFont != m_hFont)  
  37.         {  
  38.             DeleteObject(m_hFont);  
  39.             m_hFont = hDefFont;  
  40.         }  
  41.         // release temp font resource     
  42.         if (m_curFontPath.size() > 0)  
  43.         {  
  44.             wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);  
  45.             if (pwszBuffer)  
  46.             {  
  47.                 RemoveFontResource(pwszBuffer);  
  48.                 SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);  
  49.                 delete [] pwszBuffer;  
  50.                 pwszBuffer = NULL;  
  51.             }  
  52.         }  
  53.     }  
  54.     //多字节转宽字符  
  55.     wchar_t * utf8ToUtf16(std::string nString)  
  56.     {  
  57.         wchar_t * pwszBuffer = NULL;  
  58.         do   
  59.         {  
  60.             if (nString.size() < 0)  
  61.             {  
  62.                 break;  
  63.             }  
  64.             // utf-8 to utf-16  
  65.             int nLen = nString.size();  
  66.             int nBufLen  = nLen + 1;              
  67.             pwszBuffer = new wchar_t[nBufLen];  
  68.             CC_BREAK_IF(! pwszBuffer);  
  69.             memset(pwszBuffer,0,nBufLen);  
  70.             nLen = MultiByteToWideChar(CP_UTF8, 0, nString.c_str(), nLen, pwszBuffer, nBufLen);       
  71.             pwszBuffer[nLen] = '\0';  
  72.         } while (0);      
  73.         return pwszBuffer;  
  74.   
  75.     }  
  76.     //设置使用的字体和大小  
  77.     bool setFont(const char * pFontName = NULL, int nSize = 0)  
  78.     {  
  79.         bool bRet = false;  
  80.         do   
  81.         {  
  82.             //创建字体  
  83.             std::string fontName = pFontName;  
  84.             std::string fontPath;  
  85.             HFONT       hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);  
  86.             LOGFONTA    tNewFont = {0};  
  87.             LOGFONTA    tOldFont = {0};  
  88.             GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont);  
  89.             if (fontName.c_str())  
  90.             {      
  91.                 // 如果字体名称是ttf文件,取得其全路径名  
  92.                 int nFindttf = fontName.find(".ttf");  
  93.                 int nFindTTF = fontName.find(".TTF");  
  94.                 if (nFindttf >= 0 || nFindTTF >= 0)  
  95.                 {  
  96.                     fontPath = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fontName.c_str());  
  97.                     int nFindPos = fontName.rfind("/");  
  98.                     fontName = &fontName[nFindPos+1];  
  99.                     nFindPos = fontName.rfind(".");  
  100.                     fontName = fontName.substr(0,nFindPos);                  
  101.                 }  
  102.                 tNewFont.lfCharSet = DEFAULT_CHARSET;  
  103.                 strcpy_s(tNewFont.lfFaceName, LF_FACESIZE, fontName.c_str());  
  104.             }  
  105.             if (nSize)  
  106.             {  
  107.                 tNewFont.lfHeight = -nSize;  
  108.             }  
  109.             //  
  110.             GetObjectA(m_hFont,  sizeof(tOldFont), &tOldFont);  
  111.               
  112.             if (tOldFont.lfHeight == tNewFont.lfHeight  
  113.                 && ! strcpy(tOldFont.lfFaceName, tNewFont.lfFaceName))  
  114.             {  
  115.                 // already has the font   
  116.                 bRet = true;  
  117.                 break;  
  118.             }  
  119.   
  120.             // 删除旧的字体  
  121.             if (m_hFont != hDefFont)  
  122.             {  
  123.                 DeleteObject(m_hFont);  
  124.                 // release old font register  
  125.                 if (m_curFontPath.size() > 0)  
  126.                 {  
  127.                     wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);  
  128.                     if (pwszBuffer)  
  129.                     {  
  130.                         if(RemoveFontResource(pwszBuffer))  
  131.                         {  
  132.                             SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);  
  133.                         }                         
  134.                         delete [] pwszBuffer;  
  135.                         pwszBuffer = NULL;  
  136.                     }  
  137.                 }  
  138.                 fontPath.size()>0?(m_curFontPath = fontPath):(m_curFontPath.clear());  
  139.   
  140.                 if (m_curFontPath.size() > 0)  
  141.                 {  
  142.                     wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);  
  143.                     if (pwszBuffer)  
  144.                     {  
  145.                         if(AddFontResource(pwszBuffer))  
  146.                         {  
  147.                             SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);  
  148.                         }                         
  149.                         delete [] pwszBuffer;  
  150.                         pwszBuffer = NULL;  
  151.                     }  
  152.                 }  
  153.             }  
  154.             m_hFont = NULL;  
  155.   
  156.             // 字体不使用锐利字体  
  157.             tNewFont.lfQuality = ANTIALIASED_QUALITY;  
  158.   
  159.             // 创建新字体  
  160.             m_hFont = CreateFontIndirectA(&tNewFont);  
  161.             if (! m_hFont)  
  162.             {  
  163.                 // create failed, use default font  
  164.                 m_hFont = hDefFont;  
  165.                 break;  
  166.             }  
  167.               
  168.             bRet = true;  
  169.         } while (0);  
  170.         return bRet;  
  171.     }  
  172.     //取得使用当前字体写出的字符串所占据的图像大小。  
  173.     SIZE sizeWithText(const wchar_t * pszText, int nLen, DWORD dwFmt, LONG nWidthLimit)  
  174.     {  
  175.         SIZE tRet = {0};  
  176.         do   
  177.         {  
  178.             CC_BREAK_IF(! pszText || nLen <= 0);  
  179.   
  180.             RECT rc = {0, 0, 0, 0};  
  181.             DWORD dwCalcFmt = DT_CALCRECT;  
  182.   
  183.             if (nWidthLimit > 0)  
  184.             {  
  185.                 rc.right = nWidthLimit;  
  186.                 dwCalcFmt |= DT_WORDBREAK  
  187.                     | (dwFmt & DT_CENTER)  
  188.                     | (dwFmt & DT_RIGHT);  
  189.             }  
  190.             // 使用当前字体。  
  191.             HGDIOBJ hOld = SelectObject(m_hDC, m_hFont);  
  192.   
  193.             // 写字。  
  194.             DrawTextW(m_hDC, pszText, nLen, &rc, dwCalcFmt);  
  195.             SelectObject(m_hDC, hOld);  
  196.   
  197.             tRet.cx = rc.right;  
  198.             tRet.cy = rc.bottom;  
  199.         } while (0);  
  200.   
  201.         return tRet;  
  202.     }  
  203.     //创建一个指定大小的位图。  
  204.     bool prepareBitmap(int nWidth, int nHeight)  
  205.     {  
  206.         // 释放原来的位图  
  207.         if (m_hBmp)  
  208.         {  
  209.             DeleteObject(m_hBmp);  
  210.             m_hBmp = NULL;  
  211.         }       //如果大小有效则创建位图。  
  212.         if (nWidth > 0 && nHeight > 0)  
  213.         {  
  214.             m_hBmp = CreateBitmap(nWidth, nHeight, 1, 32, NULL);  
  215.             if (! m_hBmp)  
  216.             {  
  217.                 return false;  
  218.             }  
  219.         }  
  220.         return true;  
  221.     }  
  222.      //在指定位置按照指定对齐方式写字。  
  223.     //参1:字符串  
  224.     //参2:指定拉置及大小  
  225.     //参3:文字对齐方式  
  226.     int drawText(const char * pszText, SIZE& tSize, CCImage::ETextAlign eAlign)  
  227.     {  
  228.         int nRet = 0;  
  229.         wchar_t * pwszBuffer = 0;  
  230.         do   
  231.         {  
  232.             CC_BREAK_IF(! pszText);  
  233.   
  234.             DWORD dwFmt = DT_WORDBREAK;  
  235.             DWORD dwHoriFlag = eAlign & 0x0f;  
  236.             DWORD dwVertFlag = (eAlign & 0xf0) >> 4;  
  237.             //设置横向对齐方式。  
  238.             switch (dwHoriFlag)  
  239.             {  
  240.             case 1: // 左对齐  
  241.                 dwFmt |= DT_LEFT;  
  242.                 break;  
  243.             case 2: // 右对齐  
  244.                 dwFmt |= DT_RIGHT;  
  245.                 break;  
  246.             case 3: // 居中  
  247.                 dwFmt |= DT_CENTER;  
  248.                 break;  
  249.             }  
  250.             //取得字符串的字节长度。  
  251.             int nLen = strlen(pszText);  
  252.             int nBufLen  = nLen + 1;  
  253.             // 为转换后的宽字符串申请内存地址。  
  254.             pwszBuffer = new wchar_t[nBufLen];  
  255.             CC_BREAK_IF(! pwszBuffer);  
  256.             //内存数据置零  
  257.             memset(pwszBuffer, 0, sizeof(wchar_t)*nBufLen);  
  258.             // 将多字节转宽字符串。  
  259.             nLen = MultiByteToWideChar(CP_UTF8, 0, pszText, nLen, pwszBuffer, nBufLen);  
  260.             //取得写字符串占据的图像区域大小  
  261.             SIZE newSize = sizeWithText(pwszBuffer, nLen, dwFmt, tSize.cx);  
  262.             //建立RECT变量做为实际绘制占据的图像区域大小  
  263.             RECT rcText = {0};  
  264.             // 如果宽度为0,则使用显示字符串所需的图像大小。  
  265.             if (tSize.cx <= 0)  
  266.             {  
  267.                 tSize = newSize;  
  268.                 rcText.right  = newSize.cx;  
  269.                 rcText.bottom = newSize.cy;  
  270.             }  
  271.             else  
  272.             {  
  273.                 LONG offsetX = 0;  
  274.                 LONG offsetY = 0;  
  275.                 rcText.right = newSize.cx;   
  276.                 //根据对齐方式计算横向偏移。  
  277.                 if (1 != dwHoriFlag               
  278.                     && newSize.cx < tSize.cx)      
  279.                 {                                     
  280.                     offsetX = (2 == dwHoriFlag) ? tSize.cx - newSize.cx                                 : (tSize.cx - newSize.cx) / 2;                                          }  
  281.                 //如果指定矩形高度为0,则使用显示字符串所需的图像高度。  
  282.                 if (tSize.cy <= 0)  
  283.                 {  
  284.                     tSize.cy = newSize.cy;  
  285.                     dwFmt   |= DT_NOCLIP;  
  286.                     rcText.bottom = newSize.cy; // store the text height to rectangle  
  287.                 }  
  288.                 else if (tSize.cy < newSize.cy)  
  289.                 {  
  290.                     // content height larger than text height need, clip text to rect  
  291.                     rcText.bottom = tSize.cy;  
  292.                 }  
  293.                 else  
  294.                 {  
  295.                     rcText.bottom = newSize.cy;   
  296.   
  297.                     // content larger than text, need adjust vertical position  
  298.                     dwFmt |= DT_NOCLIP;  
  299.   
  300.                     //根据对齐方式计算纵向偏移。  
  301.                     offsetY = (2 == dwVertFlag) ? tSize.cy - newSize.cy     // 居下                        : (3 == dwVertFlag) ? (tSize.cy - newSize.cy) / 2   // 居中                        : 0;                                                // 居上                }  
  302.                 //如果需要,调整偏移。  
  303.                 if (offsetX || offsetY)  
  304.                 {  
  305.                     OffsetRect(&rcText, offsetX, offsetY);  
  306.                 }  
  307.             }  
  308.             //创建相应大小的位图。  
  309.             CC_BREAK_IF(! prepareBitmap(tSize.cx, tSize.cy));  
  310.             // 使用当前字体和位图  
  311.             HGDIOBJ hOldFont = SelectObject(m_hDC, m_hFont);  
  312.             HGDIOBJ hOldBmp  = SelectObject(m_hDC, m_hBmp);  
  313.             //设置背景透明模式和写字的颜色  
  314.             SetBkMode(m_hDC, TRANSPARENT);  
  315.             SetTextColor(m_hDC, RGB(255, 255, 255)); // white color  
  316.             //写字  
  317.             nRet = DrawTextW(m_hDC, pwszBuffer, nLen, &rcText, dwFmt);  
  318.             //DrawTextA(m_hDC, pszText, nLen, &rcText, dwFmt);  
  319.             //还原为之前使用的字体和位图  
  320.             SelectObject(m_hDC, hOldBmp);  
  321.             SelectObject(m_hDC, hOldFont);  
  322.         } while (0);  
  323.         //释放内存  
  324.         CC_SAFE_DELETE_ARRAY(pwszBuffer);  
  325.         return nRet;  
  326.     }  
  327.     //成员变量m_hDC及get接口  
  328.     CC_SYNTHESIZE_READONLY(HDC, m_hDC, DC);  
  329.     //成员变量m_hBmp及get接口  
  330.     CC_SYNTHESIZE_READONLY(HBITMAP, m_hBmp, Bitmap);  
  331. private:  
  332.     //友元类CCImage  
  333.     friend class CCImage;  
  334.     //成员变量m_hFont代表字体  
  335.     HFONT   m_hFont;  
  336.     //成员变量m_hWnd代表当前窗口句柄。  
  337.     HWND    m_hWnd;  
  338.     //成员m_curFontPath代表当前字体ttf文件全路径。  
  339.     std::string m_curFontPath;  
  340. };  
  341. //取得单例BitmapDC  
  342. static BitmapDC& sharedBitmapDC()  
  343. {  
  344.     static BitmapDC s_BmpDC;  
  345.     return s_BmpDC;  
  346. }  
  347. //CCImage的成员函数,使用相应的字体写字符串生成图像数据。  
  348. //参1:字符串  
  349. //参2:要创建的图片宽度,如果填0,则按照字符串的宽度进行设置。  
  350. //参3:要创建的图片高度,如果填0,则按照字符串的高度进行设置。  
  351. //参4:文字的对齐方式。  
  352. //参5:字体名称  
  353. //参6:字体大小  
  354. bool CCImage::initWithString(  
  355.                                const char *    pText,   
  356.                                int             nWidth/* = 0*/,   
  357.                                int             nHeight/* = 0*/,  
  358.                                ETextAlign      eAlignMask/* = kAlignCenter*/,  
  359.                                const char *    pFontName/* = nil*/,  
  360.                                int             nSize/* = 0*/)  
  361. {  
  362.     bool bRet = false;  
  363.     unsigned char * pImageData = 0;  
  364.     do   
  365.     {  
  366.         CC_BREAK_IF(! pText);         
  367.     //取得单例BitmapDC  
  368.         BitmapDC& dc = sharedBitmapDC();  
  369.     //设置使用的字体和大小  
  370.         if (! dc.setFont(pFontName, nSize))  
  371.         {  
  372.             CCLog("Can't found font(%s), use system default", pFontName);  
  373.         }  
  374.   
  375.         // 写字  
  376.         SIZE size = {nWidth, nHeight};  
  377.         CC_BREAK_IF(! dc.drawText(pText, size, eAlignMask));  
  378.   
  379.         //申请图像大小的内存,成功申请后将其地址返回给指针pImageData。  
  380.         pImageData = new unsigned char[size.cx * size.cy * 4];  
  381.         CC_BREAK_IF(! pImageData);  
  382.         //创建位图头信息结构  
  383.         struct  
  384.         {  
  385.             BITMAPINFOHEADER bmiHeader;  
  386.             int mask[4];  
  387.         } bi = {0};  
  388.         bi.bmiHeader.biSize = sizeof(bi.bmiHeader);  
  389.         //取得写字符串的位图像素  
  390.         CC_BREAK_IF(! GetDIBits(dc.getDC(), dc.getBitmap(), 0, 0,   
  391.             NULL, (LPBITMAPINFO)&bi, DIB_RGB_COLORS));  
  392.   
  393.         m_nWidth    = (short)size.cx;  
  394.         m_nHeight   = (short)size.cy;  
  395.         m_bHasAlpha = true;  
  396.         m_bPreMulti = false;  
  397.         m_pData     = pImageData;  
  398.         pImageData  = 0;  
  399.         m_nBitsPerComponent = 8;  
  400.         // 位图像素拷到pImageData中。   
  401.         bi.bmiHeader.biHeight = (bi.bmiHeader.biHeight > 0)  
  402.             - bi.bmiHeader.biHeight : bi.bmiHeader.biHeight;  
  403.         GetDIBits(dc.getDC(), dc.getBitmap(), 0, m_nHeight, m_pData,   
  404.             (LPBITMAPINFO)&bi, DIB_RGB_COLORS);  
  405.   
  406.         // 双循环遍历每个像素。取得R,G,B值组成4字节的RGBA值保存。  
  407.         COLORREF * pPixel = NULL;  
  408.         for (int y = 0; y < m_nHeight; ++y)  
  409.         {  
  410.             pPixel = (COLORREF *)m_pData + y * m_nWidth;  
  411.             for (int x = 0; x < m_nWidth; ++x)  
  412.             {  
  413.                 COLORREF& clr = *pPixel;  
  414.                 if (GetRValue(clr) || GetGValue(clr) || GetBValue(clr))  
  415.                 {  
  416.                     clr |= 0xff000000;  
  417.                 }  
  418.                 ++pPixel;  
  419.             }  
  420.         }  
  421.   
  422.         bRet = true;  
  423.     } while (0);  
  424.   
  425.     return bRet;  
  426. }  
  427.   
  428. NS_CC_END  

           CCImage类的代码都解析完了,其内部并没有对png,jpg,tiff做真正的解析,只是利用第三方的库进行相应的处理。经过处理后,CCImage会被图片文件的数据读取转换为Cocos2d-x所用的图像数据,存储在m_pData中。如果我们不是使用这些图片文件,那么我们就需要自已增加接口函数进行相应的处理。比如有时候做游戏不希望使用标准的图像格式以防止别人能够很容易打开图片进行查看,或者有时候将多个图片组成一个数据包。

例如:

          我们想读取一个自定义二进制图片数据(假设为Pic格式)

          (1)我们可以先定义一个新的图片类型kFmtPic,

          (2)然后定义函数

                    bool _initWithPicData(void *pData, int nDatalen);

          在其中将自定义图片文件数据pData解析到m_pData中,并设置一些属性变量。

         (3) 然后在initWithImageData函数中加入:

  1. else if (kFmtPic == eFmt)  
  2.   
  3.    //读取自定义的图片数据。  
  4.    bRet = _initWithPicData(pData, nDataLen);  
  5.    break;  


          这样我们就可以让CCImage支持将我们自已定义的图像数据包加载为Cocos2d-x支持的图像类型了。

最后,祝大家双节快乐!下课~



本节用到的图片功能库参考资料:

图像解码之一——使用libjpeg解码jpeg图片 :http://www.cnblogs.com/xiaoxiaoboke/archive/2012/02/13/2349763.html

图像解码之二——使用libpng解码png图片

http://www.cnblogs.com/xiaoxiaoboke/archive/2012/02/13/2349765.html

图像解码之三——giflib解码gif图片

http://www.cnblogs.com/xiaoxiaoboke/archive/2012/02/13/2349770.html

VC下使用LibTiff处理TIFF文件:

http://wenku.baidu.com/view/63b08afaaef8941ea76e05bc.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多