cocos2d-x 3.X 接收图片 base64 转码显示

来源:互联网 发布:c语言必读书籍 编辑:程序博客网 时间:2024/05/16 08:48

base64是一种常见的网络传输编码方式,可以对图片、文字等格式转化为二进制流。Cocos2d中自带base64码的转码、解码函数:

int cocos2d::base64Encode (const unsigned char * in, unsigned int inLength, char ** out )

int cocos2d::base64Decode (const unsigned char * in, unsigned int inLength, unsigned char ** out )


我们这里使用的是解码函数,将服务器端脚本语言(例如PHP中的 base64_encode 函数)转码后的base64码,进行解码。解码之后,因为图片格式信息未指定并不能直接保存到 .jpg 格式文件中,只能作为 raw data 给cocos2dImage 对象使用。再由 Image 对象 转化为 Texture2D 纹理对象,就可以实现对 Sprite 对象的贴图显示了。

// on "init" you need to initialize your instancebool HelloWorld::init(){    //////////////////////////////    // 1. super init first    if ( !Layer::init() )    {        return false;    }        Size visibleSize = Director::getInstance()->getVisibleSize();    Vec2 origin = Director::getInstance()->getVisibleOrigin();// getFileData 如果不指定,读取根目录是 Resource 文件夹ssize_t size = 0;unsigned char* titlech = FileUtils::getInstance()->getFileData("image.txt", "r", &size);std::string load_str;load_str = std::string((const char*)titlech,size);int len = 0;unsigned char *buffer;len = base64Decode((unsigned char*)load_str.c_str(), (unsigned int)load_str.length(), &buffer);Image* img = new Image(); bool ok = img->initWithImageData(buffer, len);Texture2D* tex = new Texture2D();tex->initWithImage(img);auto pSprite2 = Sprite::createWithTexture(tex);pSprite2->setPosition(visibleSize.width/2, visibleSize.height/2);this->addChild(pSprite2, 0);        return true;}
0 0