How can I convert an image into a Base64 string?

前端 未结 14 1185
离开以前
离开以前 2020-11-22 06:52

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

I need to know how to do it with Android, because I have to add the functionali

14条回答
  •  情深已故
    2020-11-22 07:11

    Here is code for image encoding and image decoding.

    In an XML file

    
    

    In a Java file:

    TextView textView5;
    Bitmap bitmap;
    
    textView5 = (TextView) findViewById(R.id.tv5);
    
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
    
    new AsyncTask() {
        @Override
        protected String doInBackground(Void... voids) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
            byte[] byteFormat = stream.toByteArray();
    
            // Get the Base64 string
            String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
    
            return imgString;
        }
    
        @Override
        protected void onPostExecute(String s) {
           textView5.setText(s);
        }
    }.execute();
    

提交回复
热议问题