Convert image to base64 android

2

My code what it does is take an image from the gallery and take its route in string and waiting for it in the database awaits the route of the image and displays it.

I want to be able to take a photo from the camera and also choose from the gallery and be able to show the image and that the image becomes base64 and the result await it in the database, to be able to have the possibility of doing services with web being able to send a string that is the result of the image in base64 if you do not explain it well, you can comment on it.

My code is as follows: Activity:

public class CreateBits extends AppCompatActivity {
    EditText editText;
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;
    Button nxtActivity;
    SharedPreferencesController spc;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_bits);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        editText = (EditText)findViewById(R.id.edtTextNameBit);
        spc = new SharedPreferencesController(this);
    }
    public void addBit(View view){
        String bitName = editText.getText().toString();
        App.addBits(bitName, imgDecodableString, spc.getCategoryPID());
        finish();
    }
    public void Cancell(View view){
        finish();
    }
    public void addImage(View view){
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data
                Uri selectedImage = data.getData();
                //Log.i("RegirstrarPerfil",data.toString());
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                Log.i("Main", imgDecodableString);
                ImageView imgView = (ImageView) findViewById(R.id.imgCreateBit);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

AddBits method:

public static Bits addBits(String bName, String bImage, long CID){
        long bitId;
        Log.i("App de Luis "," Bit guardado con CID "+CID);
        Number bitNumber = realm.where(Bits.class).max("bitId");
        if(bitNumber == null)
            bitId = 1;
        else
            bitId = (long)bitNumber + 1;
        realm.beginTransaction();
        Bits newBit = realm.createObject(Bits.class);
        newBit.setbitId(bitId);
        newBit.setbText(bName);
        newBit.setbImage(bImage);
        newBit.setCID(CID);
        realm.commitTransaction();
        return newBit;
    }
    
asked by Exbaby 27.04.2017 в 06:36
source

1 answer

1

This is the working code, to take a photo of the camera and gallery and convert it to base64 to be able to send the web services through its string and bitmap to show it in the app. I hope you help them.

Running.

Variables:

private  int RESULT_LOAD_IMG = 0;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
String imgDecodableString;
private String userChoosenTask;

Code to choose camera or gallery:

 public void addImage(View view){
    boolean result = CategoryUtility.checkPermission(CreateBits.this);

    //Ajustamos los elementos al DialogBox usando un AlertDialog...
    final CharSequence[] items = { "Tomar Foto", "Elegir Imagen", "Cancelar" };
    AlertDialog.Builder builder = new AlertDialog.Builder(CreateBits.this);
    builder.setTitle("Agregar Foto!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            //Se revisa los permisos de la camara para android mas actuales si el andrpoid es menor a Marshmallow
            // checkPermission() devuelve true...
            boolean result = CategoryUtility.checkPermission(CreateBits.this);
            //Comprobamos la solicitud de la camara...
            if(items[item].equals("Tomar Foto")){
                //Almacené toma la foto en la variable de cadena userChoosenTask..
                userChoosenTask = "Tomar Foto";
                if(result)
                    cameraIntent();
                //Elegir desde la galeria
            }else if (items[item].equals("Elegir Imagen")){
                userChoosenTask = "Elegir Imagen";
                if(result)
                    galleryIntent();
            }else if(items[item].equals("Cancelar")){
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
//Metodo de la camara
private void cameraIntent(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //Nos da la captura de la camara
    startActivityForResult(intent, REQUEST_CAMERA);

}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
    switch (requestCode){
        case CategoryUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                if (userChoosenTask.equals("Tomar Foto"))
                    cameraIntent();
                else if (userChoosenTask.equals("Elegir Imagen"))
                    galleryIntent();
            }else {
                //denegar
            }
            break;
    }
}
private void galleryIntent(){
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}

Processing code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK) {
            final Uri imageUri = data.getData();
            final InputStream imageStream = getContentResolver().openInputStream(imageUri);
            final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
            imgDecodableString = encodeImage(selectedImage);
            ImageView imgView = (ImageView) findViewById(R.id.imgCreateBit);
            // Set the Image in ImageView after decoding the String
            imgView.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));


            Uri selectedImages = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImages,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);

            imgDecodableString = encodeImages(imgDecodableString);
            cursor.close();
            Log.i("Main",imgDecodableString);

            imgView = (ImageView) findViewById(R.id.imgCreateBit);
            // Set the Image in ImageView after decoding the String

            Bitmap myBitmapAgain = decodeBase64(imgDecodableString);
            imgView.setImageBitmap(myBitmapAgain);


        } else {
            Toast.makeText(this, "No haz escogido una imagen",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Algo salio mal", Toast.LENGTH_LONG)
                .show();
    }
}
private String encodeImage(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
    byte[] b = baos.toByteArray();
    imgDecodableString = Base64.encodeToString(b, Base64.DEFAULT);

    return imgDecodableString;
}

public static Bitmap decodeBase64(String input)
{
    byte[] decodedBytes = Base64.decode(input.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
private String encodeImages(String path) {
    File imagefile = new File(path);
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(imagefile);
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }
    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
    byte[] b = baos.toByteArray();
    imgDecodableString = Base64.encodeToString(b, Base64.DEFAULT);
    //Base64.de
    return imgDecodableString;

}
    
answered by 28.04.2017 в 01:17