Home > other >  how to convert pdf, jpg to base64
how to convert pdf, jpg to base64

Time:08-24

I have the code below has successfully converted from image to database, I want to ask how to convert pdf to base64?

select image:

 private void selectimage() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, IMAGE);
        }

converttostring:

private String convertToString() {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            byte[] imgByte = byteArrayOutputStream.toByteArray();
            return Base64.encodeToString(imgByte, Base64.DEFAULT);
    
        }

request open file:

  @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == IMAGE && resultCode == RESULT_OK && data != null) {
                Uri path = data.getData();
    
                try {
    
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
                    gambar1.setImageBitmap(bitmap);
                    txtcekfoto.setText("SUDAH FOTO");
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
    
        }

CodePudding user response:

Select file:

Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, YOUR_REQUEST_CODE);

In onActivityResult:

...
String path = getPath(context, data.getData());
String base64String = convertToBase64(path); // Save in database

Encode pdf file to base64 string:

public static String convertToBase64(String path) {
    File file = new File(path);
    byte[] byteArray = new byte[(int) file.length()];
    try {
        FileInputStream inputStream = new FileInputStream(file);
        inputStream.read(byteArray);
        inputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

Get path:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
    String selection = null;
    String[] selectionArgs = null;
    if (needToCheckUri && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory()   "/"   split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{ split[1] };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

CodePudding user response:

After getting the file you can use this function to convert your file to base64:

   private static String encodeFileToBase64Binary(File fileName) throws IOException {
              byte[] bytes = loadFile(fileName);
              byte[] encoded = Base64.encodeBase64(bytes);
              String encodedString = new String(encoded);
              return encodedString;
         }

CodePudding user response:

You may use the code below.

File file = new File(path);
InputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
       while ((bytesRead = inputStream.read(buffer)) != -1) {
                output64.write(buffer, 0, bytesRead);
       }
} catch (IOException e) {
     e.printStackTrace();
}
output64.close();
output64.toString();
  • Related