Created
October 2, 2018 07:30
-
-
Save duangsuse/8261454d4c4157f2bb8ccf233a00d48a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color | |
import java.awt.image.BufferedImage | |
import java.net.URL | |
import javax.imageio.ImageIO | |
object Image2Ascii { | |
private fun colorAverage(image: BufferedImage, x: Int, y: Int): Color { | |
val sampleDiff = step - 1 | |
val lt = Color(image.getRGB(x, y + sampleDiff)) | |
val rt = Color(image.getRGB(x + sampleDiff, y + sampleDiff)) | |
val ld = Color(image.getRGB(x, y)) | |
val rd = Color(image.getRGB(x + sampleDiff, y)) | |
return Color(average(lt.red, rt.red, ld.red, rd.red), | |
average(lt.green, rt.green, ld.green, rd.green), | |
average(lt.blue, rt.blue, ld.blue, rd.blue)) | |
} | |
private fun average(vararg args: Int): Int { | |
val sum = args.reduce { acc, i -> acc + i } | |
return sum / args.size | |
} | |
private fun image(args: Array<out String>): BufferedImage? = ImageIO.read(URL(args.firstOrNull())) | |
private fun printAscii(r: Int, g: Int, b: Int) = print(if (average(r, g, b) <= boundary) white else black) | |
private const val black = '■' | |
private const val white = '□' | |
private const val boundary: Int = 0x7f | |
private const val step: Int = 1 | |
@JvmStatic | |
fun main(vararg args: String) { | |
val img = image(args)!! | |
println(img) | |
for (y in 0 until img.height step step) { | |
for (x in 0 until img.width step step) { | |
val ca = colorAverage(img, x, y) | |
printAscii(ca.red, ca.green, ca.blue) | |
} | |
println() | |
} | |
println("black $black white $white boundary $boundary step $step") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment