From e96eb992da53b28494f0d0d19ba0add380517713 Mon Sep 17 00:00:00 2001
From: David Motsonashvili <davidmotson@google.com>
Date: Wed, 3 Jan 2024 14:39:19 -0800
Subject: [PATCH] Change image encoding over the wire to jpeg at 80% quality

---
 .../ai/client/generativeai/internal/util/conversions.kt      | 4 ++--
 .../main/java/com/google/ai/client/generativeai/type/Part.kt | 5 ++++-
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/generativeai/src/main/java/com/google/ai/client/generativeai/internal/util/conversions.kt b/generativeai/src/main/java/com/google/ai/client/generativeai/internal/util/conversions.kt
index 19c0332c..df0d5285 100644
--- a/generativeai/src/main/java/com/google/ai/client/generativeai/internal/util/conversions.kt
+++ b/generativeai/src/main/java/com/google/ai/client/generativeai/internal/util/conversions.kt
@@ -52,7 +52,7 @@ internal fun com.google.ai.client.generativeai.type.Content.toInternal() =
 internal fun com.google.ai.client.generativeai.type.Part.toInternal(): Part {
   return when (this) {
     is com.google.ai.client.generativeai.type.TextPart -> TextPart(text)
-    is ImagePart -> BlobPart(Blob("image/png", encodeBitmapToBase64Png(image)))
+    is ImagePart -> BlobPart(Blob("image/jpeg", encodeBitmapToBase64Png(image)))
     is com.google.ai.client.generativeai.type.BlobPart ->
       BlobPart(Blob(mimeType, Base64.encodeToString(blob, BASE_64_FLAGS)))
     else ->
@@ -192,7 +192,7 @@ internal fun CountTokensResponse.toPublic() =
 
 private fun encodeBitmapToBase64Png(input: Bitmap): String {
   ByteArrayOutputStream().let {
-    input.compress(Bitmap.CompressFormat.PNG, 100, it)
+    input.compress(Bitmap.CompressFormat.JPEG, 80, it)
     return Base64.encodeToString(it.toByteArray(), BASE_64_FLAGS)
   }
 }
diff --git a/generativeai/src/main/java/com/google/ai/client/generativeai/type/Part.kt b/generativeai/src/main/java/com/google/ai/client/generativeai/type/Part.kt
index d4b7a930..4c54cc43 100644
--- a/generativeai/src/main/java/com/google/ai/client/generativeai/type/Part.kt
+++ b/generativeai/src/main/java/com/google/ai/client/generativeai/type/Part.kt
@@ -31,7 +31,10 @@ interface Part
 /** Represents text or string based data sent to and received from requests. */
 class TextPart(val text: String) : Part
 
-/** Represents image data sent to and received from requests. */
+/**
+ * Represents image data sent to and received from requests. When this is sent to the server it is
+ * converted to jpeg encoding at 80% quality.
+ */
 class ImagePart(val image: Bitmap) : Part
 
 /** Represents binary data with an associated MIME type sent to and received from requests. */