How to clear a colour from a sprite?

I have a lot of images that has a black colour that should have been made transparent instead.
For example:

I want to clear the black colour and set it transparent with cocos2dx code instead of removing the colour with image editing tools. Mainly because I have thousands of images like that and to remove the colour for each image it would take a lot of time or perhaps someone knows a tool that can help achieve this easily? I have tried to use texture packer with heuristic mask option, but it only removes the corner from corners of the image.

Just don’t create such images. Use your source file of your art. For example .psd or .ai Or which format you are using? And export png’s without black layer.

As I mentioned before: I have thousands of images like that and to remove the colour for each image it would take a lot of time.

How to achieve this by code?

Sure, what a problem to edit your sources of art of these images? If it’s yours and you have source art files?

the images are not mine, I’m just using them as testing purpose.

Don’t steal.
And for removing color you probably should use a shaders, I know a very little about them…

Never said anything about stealing. Just trying to remove colour from image by code.
It can be done by getting the image data and replacing pixels. But I don’t if its the best way to do that. Maybe using shaders would be better.

I wrote a code to clear a black colour from sprite:

cocos2d::Sprite* SpriteResource::getSprite(string spriteName, bool mask)
{
auto img = new cocos2d::Image();
img->initWithImageFile(spriteName);

    if(mask)
    {
    const uint8_t * pixels = img->getData();
    unsigned int width = img->getWidth();
    unsigned int height = img->getHeight();
    
    // Create a new pixel buffer first for exception safety's sake
    std::vector<uint8_t> newPixels(pixels, pixels + width * height * 4);
    
    auto color = cocos2d::Color4B(0,0,0,255); //color to replace
    uint8_t alpha = 0; 
    
    uint8_t* ptr = &newPixels[0];
    uint8_t* end = ptr + newPixels.size();
    while (ptr < end)
    {
        if ((ptr[0] == color.r) && (ptr[1] == color.g) && (ptr[2] == color.b) && (ptr[3] == color.a))
            ptr[3] = alpha;
        ptr += 4;
    }

    auto text = new cocos2d::Texture2D();
    text->initWithData(newPixels.data(), sizeof(newPixels.data()), cocos2d::Texture2D::PixelFormat::RGBA8888, width, height, cocos2d::Size(width, height));
    return cocos2d::Sprite::createWithTexture(text);
    }

auto texture = new cocos2d::Texture2D();
texture->initWithImage(img);
return cocos2d::Sprite::createWithTexture(texture);
}
1 Like

If you want to do it by shader then refer this post, someone helped me 2 year back :slight_smile:

1 Like