Download and save png image

Download and save png image
0.0 0


Hi everyone,
I have a problem with saving image file from url. I use HttpClient to get buffer from url and save that data to image with cocos2d::Image.
I realize sometimes the size of saved image is different from that original image. And its quality always change if the image has complex effect such as blur, glow…
Has anyone encountered this problem yet?
Here is two image. (The first one is original).

Here is the url which i downloaded from: image url
And here my code:

    HttpRequest *request = new HttpRequest();
	request->setResponseCallback([](HttpClient *client, HttpResponse *response) {
		if (response->isSucceed()) {
			auto data = response->getResponseData();
			Image *img = new Image();
			if (img->initWithImageData(reinterpret_cast<const unsigned char*>(&(data->front())), data->size())) {
				if (img->saveToFile("xxx.png", false)){


P.s: I also try to save image with RenderTexture, and I got the same result. I wonder the problem is response data or me miss something when use “saveToFile”. Sorry for my bad English. Hope you get my point.


Can’t you just directly download the file instead of loading and saving it?


It seems as if there is something messed up with the premultiplied alpha.

Why don’t you try saving the response data directly without using Image?

Something like this:

request->setResponseCallback([](HttpClient *client, HttpResponse *response) {
    if (response->isSucceed()) {
        auto data = response->getResponseData();
        FILE * fp = fopen("xxx.png", "wb");
        if (fp)
            fwrite(&(data->front()), 1, data->size(), fp);


Also I believe there is a downloader class (network/Downloader/CCDownloader.cpp) which could possibly do the job in an easier way…


Thank for your responding. Because I want put all my resources to server, and I don’t need to update my client if I want to change my resources.


Thank you so much. You saved my life!!!
I don’t know why but I DID use this method before (a long time ago), and it didn’t work for me, the image couldn’t be loaded. I and didn’t use FILE to save image again, until u suggest this.
Anyway, thank you so much.


Hi there, how do you do that.
Can you post your code ?

I’m also facing same problem.

Please help me.

Solved by using mausmausgames’s code.

thank you.