在 Kotlin 中使用 setRGB() 需要 IntArray

Using setRGB() required IntArray in Kotlin

我想在 Kotlin 中更改像素的颜色。我得到一个像素,想为其设置新值,但我在 setRGB 方法中收到一个错误,它需要 IntArray!但发现数组:

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)

此外,我正在 Kotlin/Java 中编写代码,但无法找到 setRGB() 方法如何工作的详细说明。我从 Intelij IDE 知道参数是:setRGB(x, y, width, height, IntArray for rgb color, offset, scansize).

但什么是宽、高?它是图片的尺寸吗?如果我只更改一个像素,为什么它们很重要?

以及如何将新颜色作为 IntArray 正确传递给 setRGB() 方法?

setRGB 期待原始 int[]

在 kotlin 中,java 等价于 int[]IntArray (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int-array/)

所以你应该将 val newColor 的创建更改为:

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

完整示例:

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)

有关该功能的更多信息,您可以参考 java文档:https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#setRGB(int,%20int,%20int,%20int,%20int[],%20int,%20int)

如果您(一次)仅更改一个像素,则应使用 setRGB(int x, int y, int aRGB) 方法。根本不用理会数组。

我通常不会编写 Kotlin 程序,所以语法可能不是 100% 正确,但无论如何:

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

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

也就是说,setRGB 方法的 widthheight 参数采用 int 数组,是您想要的区域的高度和宽度设置(通常是 offset == 0scansize == width)。您通常只使用它来设置多个像素。要使用它设置单个像素,值应该只是 1, 1(我从@Tom 的回答中借用了 intArrayOf 部分):

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

这应该也可以。但我认为由于数组边界检查和复制,它不太优雅并且可能更慢。