2
\$\begingroup\$

I would like to set an individual pixel in Slick (i.e Image.setPixel(x, y, r, b, g)) but I can't figure out how.

There is an Image.setPixel function but it doesn't take x and y coordinates. Any ideas?

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

You're in luck.

In Slick2D, Image has a function called getGraphics, which will return you a Slick2D graphics context.

While the graphics context does not have a setPixel function, it does have a fillRect function that you can use to set a single pixel.

Graphics g = img.getGraphics();
g.setColor(color);
g.fillRect(x,y,1,1);
g.flush();//IMPORTANT!!!

I just tried this out myself, which is how I discovered the importance of the flush call. Also check out the example ImageGraphcisTest.java in the Slick2D src folder.

\$\endgroup\$
3
  • \$\begingroup\$ A bit slow (when you are trying to set an 1000x1000 sized image with a different colour for each) but it works! Thanks! :) \$\endgroup\$
    – Darestium
    Commented Mar 10, 2012 at 0:13
  • 3
    \$\begingroup\$ In that case, I recommend only flushing once. (Amused by obious bathroom reference) \$\endgroup\$ Commented Mar 10, 2012 at 13:43
  • \$\begingroup\$ ahaha! lol, suprisingly I didn't even relate flush with a bathroom until now. \$\endgroup\$
    – Darestium
    Commented Mar 10, 2012 at 22:22
2
\$\begingroup\$

If you really want to make this from an Image object then you must:

  • Get the texture with img.getTexture()
  • Retrieve the inherent pixel data with texture.getTextureData()
  • Parse the byte-array until you reach the pixel (x, y)
  • Change the RGB value of this pixel
\$\endgroup\$
1
  • \$\begingroup\$ image(x, y) = image[y * width + x] ;) \$\endgroup\$
    – Shaun Wild
    Commented Feb 20, 2019 at 11:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .