Skip to content

Instantly share code, notes, and snippets.

@theapache64
Last active October 22, 2024 19:21
Show Gist options
  • Save theapache64/0d35c10889bb1b66cb832a8ee9ab5d92 to your computer and use it in GitHub Desktop.
Save theapache64/0d35c10889bb1b66cb832a8ee9ab5d92 to your computer and use it in GitHub Desktop.
import org.json.JSONObject
import java.io.File
const val tinyPngApiKey = "<YOUR-API-KEY-GOES-HERE>"
val projectDir = File("<PATH-TOPROJECT-ROOT>")
val supportedExtensions = listOf("png", "jpg")
fun main() {
projectDir.walk().forEach { srcFile ->
if (supportedExtensions.contains(srcFile.extension)) {
try {
val outputUrl = compress(srcFile)
println("Downloading... -> $outputUrl")
downloadAndReplace(
outputUrl,
file = srcFile // replace
)
println("✅ Saved")
} catch (e: Exception) {
println("Failed to compress: ${e.message} -> ${e.message}")
}
}
}
}
fun compress(
srcFile: File
) : String {
println("Compressing ${srcFile.absolutePath}")
val compressCurl =
"curl --user api:$tinyPngApiKey --data-binary @${srcFile.absolutePath} https://api.tinify.com/shrink"
val process = Runtime.getRuntime().exec(compressCurl)
return process.inputStream.bufferedReader().readText().let {
val joResponse = JSONObject(it)
val joInput = joResponse.getJSONObject("input")
val inputSize = joInput.getLong("size") / 1000
val joOutput = joResponse.getJSONObject("output")
val outputSize = joOutput.getLong("size") / 1000
val outputUrl = joOutput.getString("url")
println("input: $inputSize kb -> output -> $outputSize kb")
outputUrl
}
}
fun downloadAndReplace(url: String, file: File) {
val wget = "wget $url -O ${file.absolutePath}"
val process = Runtime.getRuntime().exec(wget)
val output = process.inputStream.bufferedReader().readText()
println(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment