Unable to convert pdf or docx file to base64 in android - android

I am trying to first select PDF or docx file from memory then encode Base64 String and store in mysql database. When i click on upload button, it's not work. I think there was a problem in encode, but I'm unable to solve this problem. How to solve this problem or Is there any way to solve this issue??
Below is my code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
assert uri != null;
String uriString = uri.toString();
file = new File(uriString);
filepath = file.getAbsolutePath();
String displayName ;
if(uriString.startsWith("content://"))
{
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri,null,null,null,null);
if(cursor!=null&&cursor.moveToFirst())
{
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.d("name",displayName);
}
}finally {
assert cursor != null;
cursor.close();
}
}else if(uriString.startsWith("file://"))
{
displayName = file.getName();
Log.d("name",displayName);
}
}
}
public static String convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 11];
int bytesRead;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(byteArray, Base64.NO_WRAP);
}

Indent in this way
public void getDoc() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
InputStream iStream = getContentResolver().openInputStream(selectedImage);
byte[] inputData = getBytes(iStream);
long fileSizeInBytes = inputData.length;
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
ParseFile resumes = new ParseFile("image.pdf",
inputData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

Related

Android app getting crash when select image from Recent images from gallery

My app work perfectly when select image from Pictures or images categories in Gallery but app getting crash when select image from recent images
This is my intent call
galleryLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (EasyPermissions.hasPermissions(getActivity(), perms_gallery)) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
}else {
EasyPermissions.requestPermissions(getActivity(), getString(R.string.read_file),
READ_REQUEST_CODE, perms_gallery);
}
}
});
Crash happen from here String id = wholeID.split(":")[1];
public String getPathFromUriGallery(Context context, Uri uri) {
Cursor cursor = null;
try {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
String[] filePath = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePath, sel, new String[]{id}, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
return cursor.getString(columnIndex);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
this my error log
Process: io.test.susitkMed.doctor, PID: 9576
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=3;doc=encoded=0ajgvv25pDn5wcNiiiv1YFYu7neaIdrulcWk/kBdEa8TqupNEKLhnLzz flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } }} to activity {io.test.susitkMed.doctor/io.test.susitkMed.doctor.ui.activities.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
I found this solution from this github sample https://github.com/maayyaannkk/ImagePicker
This is the solution for above issue
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
image.setImageBitmap(selectedImage);
}
}
These method use for get image url
public String getRealPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = new File(getFilename(context));
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private String getFilename(Context context) {
File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
}
Use this methods instead..
public String getImagePathFromUri(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Use Document provider instead.
For eg:
Intent it = new Intent();
it.setAction(Intent.ACTION_GET_CONTENT);
it.setType("image/*");
startActivityForResult(it, 1000);
----------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK && data != null) {
try {
Bitmap bm = getBitmapFromUri(data.getData());
iv.setImageBitmap(bm);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
When I select the image from recent then the image is broken in android | Multiple images from recent
I have mentioned below my answer link please go there and find your solutions
You can find the full post from this link || Click link here
Also, you can find here
Sample preview
Call multiple images select
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}

How to convert the uri to inputStream data and upload the stream data into server?

I am working the task in picking the file from the gallery and upload the picked file to the server.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) {
if (data != null) {
//no data present
Uri uri = data.getData();
String filePath = data.getData().getPath();
// String path = uri.getPath();
file = new File(filePath);
String name = getContentName(getContentResolver(), uri);
try {
InputStream inStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
attachFile.addView(imageView);
TextView textView = new TextView(this);
textView.setText(name);
attachFile.addView(textView);
return;
}
}
}
I poicked the file by using intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.addFlags(ST)
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST);
My issue is the uri data is converted the inputStream but i am using the ion library in that inputstream files cannot be uploaded to server.
How to convert the inputStream to outputstream to save in getCacheDir().I refered this site How to get the file path for the picked files from the external storage in android?
Please help me how to upload the InputStream data into the ion library.
In the below code i have passed the uri into the inputstream and and then crated the file and inputStream data are written in outputstream.
This works 100% try this method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) if (data != null) {
//no data present
Uri uri = data.getData();
String filePath = data.getData().getPath();
String name = getContentName(getContentResolver(), uri);
File file = new File(getCacheDir(),name);
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Log.e("InputStream Size","Size " + inputStream);
int bytesAvailable = inputStream.available();
// int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size","Size " + file.length());
inputStream.close();
outputStream.close();
file.getPath();
Log.e("File Path","Path " + file.getPath());
file.length();
Log.e("File Size","Size " + file.length());
if(file.length() > 0){
attachementImage.setVisibility(View.INVISIBLE);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
attachFile.addView(imageView);
attachFile.addView(textView);
return;
}
}
}

how to get bytes from wav in android studio

i read lots of code for read byte from wav for android studio
but i still can not get byte from wav
really need codes or demo so i can get what i need
whats wrong with my code
Resources inn = getResources();
InputStream in = inn.openRawResource(R.raw.ccheer);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[1024];
int i = 0;
try {
while (dis.available() > 0) {
music[i]=dis.readByte();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
here is my new code. still cant read byte[]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_AUDIO_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
System.out.println("Uri: " + uri);
InputStream is = new FileInputStream(getRealPathFromURI(this,uri));
}
}
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toByteArray();
}
whats wrong ? just want to read like this or other way ...
byte 00
byte 11
byte 22
...

Not able to copy image using ACTION_GET_CONTENT

I am trying to copy image using below code:
Intent intentImage = new Intent();
intentImage.setType("image/*");
intentImage.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intentImage, 10);
With this i am able to open all image content.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10) {
if (resultCode != RESULT_OK) return;
Uri selectedImageUri = data.getData();
try {
String selectedImagePath1 = getPath(selectedImageUri);
File file = new File(selectedImagePath1);
String fna = file.getName();
String pna = file.getParent();
File fileImage = new File(pna, fna);
copyFileImage(fileImage, data.getData());
} catch (Exception e) {
}
}
}
private void copyFileImage(File src, Uri destUri) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now i am successfully get path and name of the image .
Now when i run the above code then it gives me error of requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission().
so i have put the permission in manifest :
i have also defined the permission for read and write internal/external storage.
But still i am getting this error.
How can i copy image ?
Select picture using below code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
this will open gallery, after selecting pic you will get selected pic uri in below code
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 600,370, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);
String StrBase64 = Base64.encodeToString(blob.toByteArray(), Base64.DEFAULT);
imageView1.setImageBitmap(resized);
// Toast.makeText(getApplicationContext(), ""+selectedImagePath, Toast.LENGTH_LONG).show();
}
break;
}
}
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
add permission in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
this way you will get selected image in Base64 to string
Try this code-
Image will copy in SaveImage folder in sd card
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
File sel = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
SaveImage(bitmap);
}
break;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/SaveImage");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How do I compress video from URI on Android?

I want to capture video and send it to the server in base64. Before sending it, I want to check the video length and video size. I am able to capture the video
switch (v.getId()) {
case R.id.camera_button:
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, INTENT_VIDEO);
}
break;
}
}
and get the URI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == INTENT_VIDEO && resultCode == RESULT_OK) {
Uri uri = data.getData();
}
}
I am able to get a video path
private String getPath(Uri video) {
String path = video.getPath();
String[] projection = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(media, projection, null, null, null);
if (cursor.moveToFirst()) path = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
cursor.close();
return path;
}
How do I get a video object from that path so that I could compress, check video duration, file size?
For image, it will be as simple as this
BitmapFactory.decodeFile(photoPath);
and after that, I would like to convert it to base64.
For image, it's as simple as this
private String toBase64(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
byte[] bytes = outputStream.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
Currently I am doing like this
private String toBase64(Uri video) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
String path = getPath(video);
File tmpFile = new File(path);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
long length = tmpFile.length();
int inLength = (int) length;
byte[] b = new byte[inLength];
int bytesRead;
while ((bytesRead = in.read(b)) != -1) {
baos.write(b, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
I get the base64, though I don't know if it's the correct one. but, I could not check video size, duration, etc.
you can compress video using ffmpeg. this is a sample project and this is the library.

Categories

Resources