Working with Other Components in an Extension

Success!!

JAVA
import android.graphics.Bitmap;
import android.graphics.drawable.*;
import android.util.Base64;
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.ByteArrayOutputStream;


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.DEFAULT);
    }

    @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);
    }
  }

3 Likes