Last active
July 26, 2020 14:56
-
-
Save vaibhavpandeyvpz/56e018e6dfa9f107ebca615eece88c98 to your computer and use it in GitHub Desktop.
Create animated GIFs using square/gifencoder
This file contains 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 android.graphics.Bitmap | |
import com.squareup.gifencoder.* | |
import java.io.File | |
import java.io.OutputStream | |
import java.util.concurrent.TimeUnit | |
class GifBuilder(file: File, | |
width: Int, | |
height: Int, | |
private val delay: Long = 250, | |
private val unit: TimeUnit = TimeUnit.MILLISECONDS) { | |
private val encoder: GifEncoder | |
private val os: OutputStream | |
init { | |
os = file.outputStream() | |
encoder = GifEncoder(os, width, height, 0) | |
} | |
fun add(frame: Bitmap) { | |
val options = ImageOptions() | |
options.setDelay(delay, unit) | |
options.setColorQuantizer(KMeansQuantizer.INSTANCE) | |
options.setDitherer(FloydSteinbergDitherer.INSTANCE) | |
encoder.addImage(pixels(frame), options) | |
} | |
fun close() { | |
encoder.finishEncoding() | |
os.close() | |
} | |
companion object { | |
@JvmStatic | |
private fun pixels(bitmap: Bitmap): Array<IntArray> { | |
val width = bitmap.width | |
val height = bitmap.height | |
val pixels = IntArray(width * height) | |
bitmap.getPixels(pixels, 0, width, 0, 0, width, height) | |
val result = Array(width) { IntArray(height) } | |
var i = 0 | |
var x = 0 | |
while (x < width) { | |
var y = 0 | |
while (y < height) { | |
result[x][y] = pixels[i] | |
i++ | |
y++ | |
} | |
x++ | |
} | |
return result | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment