Take picture and convert to Base64
Asked Answered
B

5

31

I use code below to make a picture with camera. Instead of saving I would like to encode it to Base64 and after that pass it to another API as an input. I can't see method, how to modify code to take pictures in Base64 instead of regular files.

public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");
        }
    }
}

I try to use code below to convert an image to Base64.

public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)
{
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}

Above described should be a much more direct and easier way than saving image and after that looking for image to encode it.

Blaspheme answered 23/3, 2016 at 21:59 Comment(3)
I try to use code below to convert an image to Base64. No that code is for converting a Bitmap to base64. And you have a .jpg file. No bitmap.Chorister
newfile.createNewFile();. Remove that. The Camera app will create the file.Chorister
take pictures in Base64 instead of regular files. ?? One cannot compare base64 with a file.Chorister
F
68

Try this:
ImageUri to Bitmap:

 @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                String encodedImage = encodeImage(selectedImage);
            }
        }

Encode Bitmap in base64

   private String encodeImage(Bitmap bm)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);

        return encImage;
    }

Encode from FilePath to base64

 private String encodeImage(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();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);
        //Base64.de
        return encImage;

    }

output: enter image description here

Fishwife answered 23/3, 2016 at 22:9 Comment(5)
This code makes a bitmap from a jpg file. Then the bitmap is concerted to jpg again. Finally the jpg is base64 encoded. Better omit the bitmap. Just base64 encode the .jpg file directly.Chorister
Moreover there is still a file saved by the camera app. OP asked for something without a file.Chorister
But first of all, I cannot see the file. I am using TC for searching it, but it is nowhere.Blaspheme
How do you go back, String to Bitmap or Uri?Haymaker
i convert this code on kotlin but this not working now .Dett
M
3

I've wrote my code like this :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Camera mCamera = Camera.open();
        mCamera.startPreview();// I don't know why I added that, 
                               // but without it doesn't work... :D

        mCamera.takePicture(null, null, mPicture);
    }

    private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            System.out.println("***************");
            System.out.println(Base64.encodeToString(data, Base64.DEFAULT));
            System.out.println("***************");
        }
    };
}

It works perfectly...

Missi answered 24/6, 2017 at 11:37 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this how-to-answer for providing quality answer.Leeuwenhoek
O
2

Just for converting from bitmap to base64 string in kotlin I use:

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }
Ornithischian answered 20/2, 2020 at 12:19 Comment(0)
U
1

If you want your base64 String to follow the standard format, add this after getting your base64 method from any of the provided answers

String base64 =""; //Your encoded string
base64 = "data:image/"+getMimeType(context,profileUri)+";base64,"+base64;

The method to get imageExtension is

   public static String getMimeType(Context context, Uri uri) {
        String extension;
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //If scheme is a content
            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
        }
        return extension;
    }
Unclasp answered 9/7, 2020 at 10:50 Comment(2)
what is profileUri? where is defined?!!Solutrean
profileUri is the uri of your bitmap. You can check this answer on how to get uri from bitmap https://mcmap.net/q/352491/-how-can-i-transform-a-bitmap-into-a-uriUnclasp
D
1

  try {
                    val imageStream: InputStream? = requireActivity().getContentResolver().openInputStream(mProfileUri)
                    val selectedImage = BitmapFactory.decodeStream(imageStream)
                    val baos = ByteArrayOutputStream()
                    selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                    val b = baos.toByteArray()
                    val encodedString: String = Base64.encodeToString(b,Base64.DEFAULT)

                    Log.d("check string" ,encodedString.toString())

                } catch (e: IOException) {
                    e.printStackTrace()
                }

For kotlin use code is given bellow just copy this and give image uri at "mProfileUri"
Dett answered 1/7, 2022 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.