This repository has been archived by the owner on Jul 8, 2022. It is now read-only.
/
NativeImage.kt
52 lines (42 loc) · 1.9 KB
/
NativeImage.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.soywiz.korim.bitmap
import com.soywiz.korim.format.ImageEncodingProps
import com.soywiz.korim.format.PNG
import com.soywiz.korim.format.nativeImageFormatProvider
import com.soywiz.korim.vector.Context2d
import com.soywiz.korio.crypto.Base64
import com.soywiz.korio.lang.printStackTrace
abstract class NativeImage(width: Int, height: Int, val data: Any?, premultiplied: Boolean) : Bitmap(width, height, 32, premultiplied) {
abstract val name: String
abstract fun toNonNativeBmp(): Bitmap
override fun swapRows(y0: Int, y1: Int) = throw UnsupportedOperationException()
fun toBmp32(): Bitmap32 = toNonNativeBmp().toBMP32()
open fun toUri(): String = "data:image/png;base64," + Base64.encode(PNG.encode(this, ImageEncodingProps("out.png")))
override fun toString(): String = "$name($width, $height)"
}
fun Bitmap.mipmap(levels: Int): NativeImage = nativeImageFormatProvider.mipmap(this, levels)
fun Bitmap.toUri(): String {
if (this is NativeImage) return this.toUri()
return "data:image/png;base64," + Base64.encode(PNG.encode(this, ImageEncodingProps("out.png")))
}
fun NativeImage(width: Int, height: Int) = nativeImageFormatProvider.create(width, height)
fun NativeImage(width: Int, height: Int, d: Context2d.Drawable, scaleX: Double = 1.0, scaleY: Double = scaleX): NativeImage {
val bmp = NativeImage(width, height)
try {
val ctx = bmp.getContext2d()
ctx.keep {
ctx.scale(scaleX, scaleY)
ctx.draw(d)
}
} catch (e: Throwable) {
e.printStackTrace()
}
return bmp
}
fun NativeImage(d: Context2d.SizedDrawable, scaleX: Double = 1.0, scaleY: Double = scaleX): NativeImage {
return NativeImage((d.width * scaleX).toInt(), (d.height * scaleY).toInt(), d, scaleX, scaleY)
}
fun Bitmap.ensureNative() = when (this) {
is NativeImage -> this
else -> nativeImageFormatProvider.copy(this)
}
fun Context2d.SizedDrawable.raster(scaleX: Double = 1.0, scaleY: Double = scaleX) = NativeImage(this, scaleX, scaleY)