How to Reduce an Image File Size Before Uploading to a Server

Resize image file before uploading to server using Retrofit2

I'm using this object to compress an image to 1Mo max. You can use it or adjust it to your needs

/**
* Definition of the BitmapUtils object.
*/
object BitmapUtils {
const val ONE_KO = 1024
const val ONE_MO = ONE_KO * ONE_KO

/**
* Compress, if needed, an image file to be lower than or equal to 1 Mo
*
* @param filePath Image file path
*
* @return Stream containing data of the compressed image. Can be null
*/
fun compressedImageFile(filePath: String): InputStream? {
var quality = 100
var inputStream: InputStream? = null
if (filePath.isNotEmpty()) {
var bufferSize = Integer.MAX_VALUE
val byteArrayOutputStream = ByteArrayOutputStream()
try {
val bitmap = BitmapFactory.decodeFile(filePath)
do {
if (bitmap != null) {
byteArrayOutputStream.reset()
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream)
bufferSize = byteArrayOutputStream.size()
logD { "quality: $quality -> length: $bufferSize" }
quality -= 10
}
} while (bufferSize > ONE_MO)
inputStream = ByteArrayInputStream(byteArrayOutputStream.toByteArray())
byteArrayOutputStream.close()
} catch (e: Exception) {
logE { "Exception when compressing file image: ${e.message}" }
}
}
return inputStream
}
}

To create a file from the InputStream, you can use this extension:

fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}

And to use it:

var file = File(YOUR_PATH)
file.copyInputStreamToFile(BitmapUtil.compressedImageFile(filePath))

Javascript resize image to reduce its size before uploading to the server?

According to this link you can use the native JavaScript and HTML5 Canvas features to resize an image on the client-side. I have not tried the instructions in this tutorial but I have used HTML5 Canvas in the past to make a 2D RPG engine that resized images. This tutorial, however, goes further and explains how to create an image for the purposes that you are asking for. Looking over this tutorial, it also provides alternatives if your native browser doesn't support certain features, like "toBlob".

How to compress image before uploading to server

You can use below to compress bitmap

for jpeg images

Bitmap original = BitmapFactory.decodeStream(getAssets().open("imagg1.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

and for png images

Bitmap original = BitmapFactory.decodeStream(getAssets().open("imagg1.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));


Related Topics



Leave a reply



Submit