Home > OS >  Using setRGB() required IntArray in Kotlin
Using setRGB() required IntArray in Kotlin

Time:11-01

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?

CodePudding user response:

setRGB expect a primitive int[]

In kotlin the java equivalent of int[] is IntArray (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int-array/)

So you should change the creation of val newColor to:

val newColor = intArrayOf(color.red, 0, 0)

Full example:

val c: Int = bufferedImage.getRGB(x, y)
val color = Color(c)

val newColor = intArrayOf(color.red, 0, 0)
bufferedImage.setRGB(x, y, 0, 0, newColor, 0, 0)

For more info regarding the function you can refer to the javadoc: https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#setRGB(int, int, int, int, int[], int, int)

CodePudding user response:

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.

  • Related