coco2dx加载网络图片并保存

直接上代码

bool HelloWorld::init()

{

    //////////////////////////////

    // 1. super init first

    if ( !Layer::init() )

    {

        return false;

    }



    HttpRequest* request = new HttpRequest();

    request->setUrl("http://neoimaging.beareyes.com.cn/png2/ni_png_2_1518.png");

    request->setRequestType(HttpRequest::Type::GET);

    request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));

    request->setTag("GET test1");

    HttpClient::getInstance()->send(request);

    request->release();



    return true;

}



void HelloWorld::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)

{

    if (!response)

    {

        return;

    }

    

    // You can get original request type from: response->request->reqType

    if (0 != strlen(response->getHttpRequest()->getTag())) 

    {

        log("%s completed", response->getHttpRequest()->getTag());

    }

    int statusCode = response->getResponseCode();

    if (!response->isSucceed()) 

    {

        log("response failed");

        log("error buffer: %s", response->getErrorBuffer());

        return;

    }



    //get data

    std::vector<char> *buffer = response->getResponseData();



    //create image

    CCImage* img = new CCImage;

    img->initWithImageData((unsigned char*)buffer->data(),buffer->size());

    

    //create texture

    cocos2d::CCTexture2D* texture = new CCTexture2D();

    bool isImg = texture->initWithImage(img);

    img->release();



    //create sprite

    CCSprite* sprite = CCSprite::createWithTexture(texture);

    texture->release();

    sprite->setPosition(ccp(100,100));

    addChild(sprite,100);



    //write file

    std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();

    path+="download_image.png";



    FILE *fp = fopen(path.c_str(), "wb+");

    fwrite(buffer->data(), 1,buffer->size(), fp);

    fclose(fp);

}

 

你可能感兴趣的:(图片)