Android Resize Image Save To File With Glide

Jun 18, 2018

Downsample Strategy:

  • downsample(DownsampleStrategy.AT_MOST) is more memory efficient, but width and height might be smaller than specified specified size
  • downsample(DownsampleStrategy.CENTER_INSIDE) ensure longer side always match specified size
  • with override(size) only without downsample strategy, the shorter side always match specified size (I assume downsample(DownsampleStrategy.AT_LEAST) is used as default)

Use .skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE) if this is a one-time operation to avoid caching.

fun reizeImageFileWithGlide(file: File, outputFile: File, size: Int) { // : Deferred<File>    var bitmap = Glide.with(application)            .asBitmap()            .load(file)            // .apply(RequestOptions().override(size))            // .apply(RequestOptions().override(size).downsample(DownsampleStrategy.AT_MOST))            .apply(RequestOptions().override(size).downsample(DownsampleStrategy.CENTER_INSIDE).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))            .submit().get()    val out = FileOutputStream(outputFile)    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)    out.flush()    out.close()    Helper.copyExif(file.absolutePath, outputFile.absolutePath)}

Use kotlin coroutines or any threading library because .submit().get() is blocking.

launch {    try {      reizeImageFileWithGlide(...)     }    catch (e: Exception) {    }}

If you prefer callback, use .into with SimpleTarget.

fun reizeImageFileWithGlide(file: File, outputFile: File, size: Int) { // : Deferred<File>    Glide.with(application)            .asBitmap()            .load(file)            // .fitCenter()            .into(object : SimpleTarget<Bitmap>(size, size) {                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {                    try {                        val out = FileOutputStream(outputFile)                        resource.compress(Bitmap.CompressFormat.JPEG, 85, out)                        out.flush()                        out.close()                    }                    catch (e: IOException) {                        // handle exception                    }                }                override fun onLoadFailed(errorDrawable: Drawable?) {                    // handle exception                }            })}


❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.