Take image from gallery and convert to base64 issue

前端 未结 4 1456
醉话见心
醉话见心 2021-01-03 14:13

sorry for asking silly question.but it solved yet my me.please help i had tried all codes on stackoverflow and follow other tutorial but it wont help at all.i am taking imag

4条回答
  •  庸人自扰
    2021-01-03 14:55

    This is how I do it on my onActivityResult of my gallery intent.

    String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());

    Then converting the whole thing to bitmap.

    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    

    Here is my getRealPathFromURI method from ImageUtil Class.

    public static String getRealPathFromURI(Context context, Uri contentURI) {
            String result = null;
                String[] projection = {MediaStore.Images.Media.DATA};
    
                try {
                    Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
                    cursor.moveToFirst();
    
                    int columnIndex = cursor.getColumnIndex(projection[0]);
                    result = cursor.getString(columnIndex);
                    cursor.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
        }
    

    And here is my conversion from bitmap to base64.

    public static String getBase64(Bitmap bitmap) {
    if (bitmap != null) {
    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    
    
       return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
    }
    
    return null;
    }
    

提交回复
热议问题