package uk.co.metricrat.imagebase64; import android.graphics.*; import android.graphics.drawable.*; import android.util.*; import android.widget.*; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.runtime.*; import java.io.*; import java.net.*; import static org.acra.ACRA.LOG_TAG; public class ImageBase64 extends AndroidNonvisibleComponent { public ImageBase64(ComponentContainer container) { super(container.$form()); } @SimpleFunction(description = "Get Image and returns base64 string") public void GetImageAsBase64(Image image ) throws Exception { final ImageView imageView = (ImageView) image.getView(); Bitmap imageBitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); String encodedString = bitMapToBase64(imageBitmap); AfterImageBase64(encodedString); } public String bitMapToBase64(Bitmap bitMap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitMap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); return Base64.encodeToString(byteArray, Base64.NO_WRAP); } @SimpleEvent(description = "Called after the image is converted. The text argument `imageBase64Data` is the base64 string of the image") public void AfterImageBase64(String imageBase64Data) { EventDispatcher.dispatchEvent(this, "AfterImageBase64", imageBase64Data); } @SimpleFunction(description="Set Image component with image from base64 string") public void SetImageFromBase64(final Image image, String base64String) { final ImageView imageView = (ImageView) image.getView(); byte[] decodedString = Base64.decode(base64String, Base64.NO_WRAP); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); imageView.setImageBitmap(decodedByte); } // Encodes the given text value so that it can be used in a URL. @SimpleFunction(description = "Encodes the given text value so that it can be used in a URL") public String UriEncode(String text) { try { return URLEncoder.encode(text, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(LOG_TAG, "UTF-8 is unsupported?", e); return ""; } } }