All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.ru.casperix.multiplatform.loader.JvmLoaders.kt Maven / Gradle / Ivy

The newest version!
package ru.casperix.multiplatform.loader

import ru.casperix.renderer.pixel_map.PixelMap
import ru.casperix.signals.concrete.EitherFuture
import ru.casperix.signals.concrete.EitherSignal
import ru.casperix.multiplatform.loader.JvmImageConverter.createPixelMap
import java.io.File
import javax.imageio.ImageIO

actual val resourceLoader: AbstractResourceLoader = JvmLoaders()

class JvmLoaders : CachedResourceLoader() {

    override fun saveImage(path: String, pixelMap: PixelMap): ResourceSaveError? {
        val image = JvmImageConverter.createBufferedImage(pixelMap)
        val file = File(path)
        file.mkdirs()
        ImageIO.write(image, "png", file)
        return null
    }

    override fun loadBytesDirect(path: String): EitherFuture {
        val loader = EitherSignal()
        val classloader = Thread.currentThread().getContextClassLoader()
        val stream = classloader.getResourceAsStream(path)

        loader.apply {
            if (stream == null) {
                reject(ResourceNotFoundLoadError(path))
            } else {
                accept(stream.readBytes())
            }
        }
        return loader
    }

    override fun loadImageDirect(path: String): EitherFuture {
        val loader = EitherSignal()
        try {
            val classloader = Thread.currentThread().getContextClassLoader()
            val url = classloader.getResource(path)
            if (url === null) {
                loader.reject(ResourceNotFoundLoadError(path))
                return loader
            }
            val image = ImageIO.read(url)
            val pixelMap = createPixelMap(image, path)

            loader.accept(pixelMap)
        } catch (e: Throwable) {
            loader.reject(ResourceCustomLoadError(e.message ?: ""))
        }
        return loader
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy