ImageConverter.kt 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package io.github.zadam.triliumsender.services
  2. import android.graphics.Bitmap
  3. import android.graphics.BitmapFactory
  4. import java.io.ByteArrayInputStream
  5. import java.io.ByteArrayOutputStream
  6. import java.io.InputStream
  7. class ImageConverter {
  8. fun scaleImage(inputStream: InputStream, mimeType: String): InputStream {
  9. // we won't do anything with GIFs, PNGs etc. This is minority use case anyway
  10. if (mimeType != "image/jpeg") {
  11. return inputStream;
  12. }
  13. val options = BitmapFactory.Options()
  14. val bitmap = BitmapFactory.decodeStream(inputStream, null, options)
  15. val maxWidth = 2000
  16. val maxHeight = 2000
  17. val scale = Math.min(maxHeight.toFloat() / bitmap.width, maxWidth.toFloat() / bitmap.height)
  18. val newWidth: Int = if (scale < 1) (bitmap.width * scale).toInt() else bitmap.width;
  19. val newHeight: Int = if (scale < 1) (bitmap.height * scale).toInt() else bitmap.height;
  20. val scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
  21. val baos = ByteArrayOutputStream()
  22. scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos)
  23. val bitmapdata = baos.toByteArray()
  24. return ByteArrayInputStream(bitmapdata)
  25. }
  26. }