scoop:scoop.graphics:0.1.0
src/drawing/image.scoop
Selected production source · src/drawing/image.scoop
1
package scoop.graphics3
public enum ImageSampling {4
Nearest, Linear5
}7
/** Immutable pixels with a color space; GPU images retain their compatible context. */8
public class Image internal constructor(internal val resource: GraphicsResource) : Closeable {9
/** Samples this image in pixel coordinates, clamping at its edges. */10
public fun toShader(sampling: ImageSampling = ImageSampling.Linear): Shader {11
@Unsafe {12
return Shader(13
ownedGraphics(14
imageShader(resource.get(), sampling == ImageSampling.Linear),15
"create image shader"16
)17
)18
}19
}20
public val width: Int21
get() {22
@Unsafe23
{24
return imageDimension(resource.get(), false)25
}26
}27
public val height: Int28
get() {29
@Unsafe30
{31
return imageDimension(resource.get(), true)32
}33
}34
public val isClosed: Boolean get() = resource.isClosed35
public override fun close() {36
resource.close()37
}38
public companion object {39
/** Copies tightly packed, straight-alpha RGBA8 input. */40
public fun fromRgba(width: Int, height: Int, pixels: Array<Byte>): Image {41
requireGraphics(42
pixels.size == pixelBytes(width, height),43
"RGBA byte length does not match image size"44
)45
@Unsafe46
{47
return pixels48
.withDataPointer { bytes, _ ->49
@Unsafe50
{51
return@withDataPointer Image(52
ownedGraphics(imageRgba(width, height, bytes), "create RGBA image")53
)54
}55
}56
}57
}58
/**59
* Decodes complete PNG or JPEG pixels and applies the encoded orientation.60
* A codec error or incomplete pixel data reports GraphicsException; partial images are61
* never returned. The result owns its decoded CPU pixels independently of encoded.62
*/63
public fun decode(encoded: Array<Byte>): Image {64
@Unsafe65
{66
return encoded67
.withDataPointer { bytes, count ->68
@Unsafe69
{70
return@withDataPointer Image(71
ownedGraphics(imageDecode(bytes, count), "decode image")72
)73
}74
}75
}76
}77
}78
}80
internal fun pixelBytes(width: Int, height: Int): Long {81
requireGraphics(width > 0 && height > 0, "image dimensions must be positive")82
val pixels = width.toLong() * height.toLong()83
requireGraphics(pixels <= Long.MAX_VALUE / 4L, "pixel allocation size overflow")84
return pixels * 4L85
}87
@Extern(name = "scoop_graphics_image_dimension")88
private fun imageDimension(image: Ptr<Unit>, height: Boolean): Int90
@Extern(name = "scoop_graphics_image_rgba")91
private fun imageRgba(width: Int, height: Int, pixels: Ptr<Byte>): Ptr<Unit>?93
@Extern(name = "scoop_graphics_image_decode")94
private fun imageDecode(bytes: Ptr<Byte>, count: Long): Ptr<Unit>?96
@Extern(name = "scoop_graphics_image_shader")97
private fun imageShader(image: Ptr<Unit>, linear: Boolean): Ptr<Unit>?