简体   繁体   English

从URL获取图像,在Cocos2dx C ++中使用curl

[英]Getting Image From URL , Using curl in Cocos2dx C++

I am using curl in C++ to get an Image from a URL for a Cocos2dx Game. 我在C ++中使用curl从Cocos2dx游戏的URL获取图像。 The Code is Working Fine. 该代码工作正常。 And using CCImage And cocos2d::CCTexture2D I create a Sprite and Add it on my Layer. 并使用CCImagecocos2d::CCTexture2D创建一个Sprite并将其添加到我的图层上。

The Sprite is definitely getting added on the Layer, (I Know it because if i try to Add the Same Sprite It is getting crashed Stating Child already Added But its is no where to be found on Layer. I tried changing the BG Color, ZIndex of Sprite But the sprite is not visible. Sprite肯定是在图层上添加的,(我知道,因为如果我尝试添加相同的Sprite,它就会崩溃,说明Child already Added但是在Layer上找不到它。我尝试更改BG颜色,ZIndex Sprite的图片,但是sprite不可见。

here is the code: 这是代码:

void HelloWorld::getImageFromURL(const char* url)
{
    CURL *curl;       // CURL objects
    CURLcode res;
    MemoryStruct buffer; // memory buffer

    curl = curl_easy_init(); // init CURL library object/structure

    if(curl) {

        // set up the write to memory buffer
        // (buffer starts off empty)

        buffer.memory = NULL;
        buffer.size = 0;

        stringstream urlString;
        urlString<<url;
        // (N.B. check this URL still works in browser in case image has moved)

        CCLog("%s", urlString.str().c_str());

        curl_easy_setopt(curl, CURLOPT_URL, urlString.str().c_str());
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); // tell us what is happening

        // tell libcurl where to write the image (to a dynamic memory buffer)

        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, Utility::WriteMemoryCallback);
        curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *) &buffer);

        // get the image from the specified URL

        res = curl_easy_perform(curl);
        CCLog("Curl code: %i", res);

        CCImage* img = new CCImage();
        img->initWithImageData((void*)buffer.memory, (long)buffer.size, CCImage::kFmtPng);
        cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D(); //TODO:: leak
        texture->initWithImage(img);


        CCSprite* sprite = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 256, 256));
        sprite->setPosition(CENTRE_OF_SCREEN);
        sprite->setContentSize(CCSize(256,256));
        sprite->setAnchorPoint(ccp(0, 0));
        this->addChild(sprite,1000,1000);

        curl_easy_cleanup(curl);
        free(buffer.memory);


    }

}

Any Help will be Greatly Appreciated. 任何帮助将不胜感激。

Thanks a ton W 一吨W

Check the CURL code you are receiving, I got problems getting the image because of domains restrictions or because the URL wasn't from an image. 检查您收到的CURL代码,由于域限制或URL不是来自图像,因此获取图像时出现问题。 I tested it from different URLs and I could deduce the problem from there. 我从不同的URL进行了测试,可以从那里推断出问题所在。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM