I have a sprite sheet (image) and want to draw it on screen.

image  = sprite sheet image
x      = player x position
y      = player y position
width  = player width
height = player height

public class main extends japplet

    public void paint(Graphics g)
        g.drawImage(image, x, y, x+width, y+height, 
                   0, 0, 40, 40 ,sprite_sheet.m1);

On the sprite sheet, I have the image of a player with a blue background color. Calling drawImage shows the blue background too. I could remove the color with Photoshop, but I really don't want to, because it would remove part of my player.

Can I remove the background color with Java code?

  • 1
    \$\begingroup\$ Are you really having that big a problem using Photoshop that you think it'd be easier to do this programmatically? Anyway, this is a question for StackOverflow \$\endgroup\$ Mar 23 '13 at 3:26
  • \$\begingroup\$ This should help stackoverflow.com/questions/14097386/… \$\endgroup\$
    – Savlon
    Mar 23 '13 at 13:57
  • 1
    \$\begingroup\$ What exactly do you mean by "it will remove part of my player"? If you (as a person) cannot remove the color in Photoshop, how is an algorithm supposed to do it automatically? \$\endgroup\$
    – Thomas
    Mar 24 '13 at 5:38
  • 1
    \$\begingroup\$ It might help if you included a picture of your actual sprite, and some hint of how you want it to look like in the game (and maybe an example of what goes wrong when you try to remove the background in Photoshop). \$\endgroup\$ Mar 24 '13 at 13:22

It seems you want to do some color keying, which Java cannot do on the fly with the Graphics2D library you are using. Due to this, you will need to create the alpha channel yourself, move to something that has color key support (SDL). Most engines nowadays do not support this operation as it is computationally expensive and you will need to do this "on the fly" to convert it anyway.

I have a nice answer here on why you should use alpha transparency instead.

If you have a large code base or insist on writing your rendering back end in Java2D with color key mapped images, then you can always decide to do something by hand. As linked in the comments, there is a a good post on StackOverflow on how to do this here.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.