All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
jvmMain.ru.casperix.multiplatform.loader.JvmImageConverter.kt Maven / Gradle / Ivy
package ru.casperix.multiplatform.loader
import ru.casperix.multiplatform.put
import ru.casperix.renderer.pixel_map.PixelMap
import java.awt.AlphaComposite
import java.awt.Transparency
import java.awt.color.ColorSpace
import java.awt.image.*
@ExperimentalUnsignedTypes
object JvmImageConverter {
/**
*
* @see stackoverflow
*/
fun createPixelMap(image: BufferedImage, name:String): PixelMap {
val bytes = getRGBA(image)
return PixelMap.RGBA(image.width, image.height, bytes.toUByteArray(), name)
}
private fun getRGBA(image: BufferedImage): ByteArray {
val colorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
true,
false,
Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE
)
val raster = Raster.createInterleavedRaster(
DataBuffer.TYPE_BYTE,
image.width,
image.height,
image.width * 4,
4,
intArrayOf(0, 1, 2, 3),
null
) // R, G, B, A order
val imageRGBA = BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied, null)
val bytesRGBA = (raster.dataBuffer as DataBufferByte).data
// Draw the image onto the RGBA buffer, which will be updated immediately
val g = imageRGBA.createGraphics()
try {
g.composite = AlphaComposite.Src
g.drawImage(image, 0, 0, null)
} finally {
g.dispose()
}
return bytesRGBA
}
fun createBufferedImage(pixelMap: PixelMap): BufferedImage {
val colorModel = ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
true,
false,
Transparency.TRANSLUCENT,
DataBuffer.TYPE_BYTE
)
val raster = Raster.createInterleavedRaster(
DataBuffer.TYPE_BYTE,
pixelMap.width,
pixelMap.height,
pixelMap.width * 4,
4,
intArrayOf(0, 1, 2, 3),
null
) // R, G, B, A order
val image = BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied, null)
val imageBytes = (raster.dataBuffer as DataBufferByte).data
if (imageBytes.size != pixelMap.bytes.size) {
throw Exception("Invalid pixelmap size")
}
imageBytes.put(pixelMap.bytes.data.toByteArray(), 0)
return image
}
}