Scoop API

scoop:scoop.graphics:0.1.0

src/drawing/image.scoop

Selected production source · src/drawing/image.scoop

1package scoop.graphics
3public enum ImageSampling {
4 Nearest, Linear
5}
7/** Immutable pixels with a color space; GPU images retain their compatible context. */
8public 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: Int
21 get() {
22 @Unsafe
23 {
24 return imageDimension(resource.get(), false)
25 }
26 }
27 public val height: Int
28 get() {
29 @Unsafe
30 {
31 return imageDimension(resource.get(), true)
32 }
33 }
34 public val isClosed: Boolean get() = resource.isClosed
35 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 @Unsafe
46 {
47 return pixels
48 .withDataPointer { bytes, _ ->
49 @Unsafe
50 {
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 are
61 * never returned. The result owns its decoded CPU pixels independently of encoded.
62 */
63 public fun decode(encoded: Array<Byte>): Image {
64 @Unsafe
65 {
66 return encoded
67 .withDataPointer { bytes, count ->
68 @Unsafe
69 {
70 return@withDataPointer Image(
71 ownedGraphics(imageDecode(bytes, count), "decode image")
72 )
73 }
74 }
75 }
76 }
77 }
80internal 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 * 4L
87@Extern(name = "scoop_graphics_image_dimension")
88private fun imageDimension(image: Ptr<Unit>, height: Boolean): Int
90@Extern(name = "scoop_graphics_image_rgba")
91private fun imageRgba(width: Int, height: Int, pixels: Ptr<Byte>): Ptr<Unit>?
93@Extern(name = "scoop_graphics_image_decode")
94private fun imageDecode(bytes: Ptr<Byte>, count: Long): Ptr<Unit>?
96@Extern(name = "scoop_graphics_image_shader")
97private fun imageShader(image: Ptr<Unit>, linear: Boolean): Ptr<Unit>?