Issue
I want to change color of a pixel in Kotlin. I get a pixel, want to set new values for it but I get an error in setRGB method that it requires IntArray! but found Array:
val c: Int = bufferedImage.getRGB(x, y)
val color = Color(c)
val newColor = Array<Int>(3) { color.red; 0; 0 }
bufferedImage.setRGB(x, y, 0, 0, newColor, 0, 0)
Also, I am writing code in Kotlin/Java and cannot find detailed explanation how does setRGB() method work. I know from Intelij IDE that parameters are: setRGB(x, y, width, height, IntArray for rgb color, offset, scansize).
But what is width, height? Is it dimensions of a picture? Why do they matter if I only change one pixel?
And how do I pass new color to setRGB() method correctly as IntArray?
Solution
If you are only changing one pixel (at a time), you should use the setRGB(int x, int y, int aRGB)
method. Don't bother with arrays at all.
I don't normally program Kotlin, so the syntax may not be 100% correct, but anyway:
val c: Int = bufferedImage.getRGB(x, y)
val color = Color(c)
val newColor = Color(color.red, 0, 0)
bufferedImage.setRGB(x, y, newColor.getRGB())
That said, the width
and height
parameters of the setRGB
method that takes an int
array, is the height and with of the region you want to set (and usually offset == 0
and scansize == width
) . You typically use this only to set multiple pixels. To set a single pixel using it, the values should be simply 1, 1
(I borrowed the intArrayOf
part from @Tom's answer):
val newColor = intArrayOf(color.red, 0, 0)
bufferedImage.setRGB(x, y, 1, 1, newColor, 0, 1)
This should also work. But I think it's less elegant and probably slower due to array bounds checking and copying.
Answered By - Harald K
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.