Upload pdf or txt in app android and convert to base64 - android

I'm working for an application in witch i need to upload a file ( image from camera or gallery, pdf or txt from documents), convert in base64 and add the String with the base64 in an array. I resolved for image both from camera and from gallery- Now i need to do the same with the documents. How ca I upload a document from my device to my app and convert it in base64? This is my code for images:
private void selectImage(){
final CharSequence[] item={"Camera","Document","Cancel"};
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Carica");
builder.setItems(item, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(item[i].equals("Camera")){
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,Request_camera);
}
else if(item[i].equals("Document")){
Intent intent3 = new Intent();
intent3.setType("*/*");
intent3.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent3,"Choose File to Upload.."),PICK_FILE_REQUEST);
Uri.parse(Environment.getExternalStorageDirectory().toString());
}
else if(item[i].equals("Cancel")){
dialog.dismiss();
}
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==Request_camera && button1==1){
Bundle bundle=data.getExtras();
final Bitmap bpm= (Bitmap)bundle.get("data");
uploadImage.setImageBitmap(bpm);
bitmapToBase64(bpm);
String mynewString=bitmapToBase64(bpm);
mydocument.set(0,mynewString);
decode64.setText(mynewString);
getFileExt(uploadImage.toString());
}
else if(requestCode==Request_camera && button1==2){
Bundle bundle=data.getExtras();
final Bitmap bpm= (Bitmap)bundle.get("data");
imageView2.setImageBitmap(bpm);
bitmapToBase64(bpm);
String mynewString=bitmapToBase64(bpm);
decodee2.setText(mynewString);
decodee2.setTextColor(Color.GREEN);
}
else if(requestCode==Request_file){
Uri selectImageUri=data.getData();
uploadImage.setImageURI(selectImageUri);
String newNome=getFileName(selectImageUri);
decode64.setText(newNome);
String realPath=selectImageUri.toString();
decodee2.setText(realPath);
File file=new File(newNome);
getStringFile(file);
String myDecode=getStringFile(file);
mydocument.set(0,myDecode);
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
Thanks!!

To convert your image to Base64;
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageByte, Base64.DEFAULT);
}
You need first to convert it to bitmap.

Related

Improve quality of programmatically captured image in the android app [duplicate]

This question already has answers here:
data.getExtras().get("data") result of low resolution image in android
(2 answers)
Closed 4 years ago.
I integrated camera in my application and using that camera the captured image is blur. Any suggestions for improving captured image quality.
I am using multipart for sending image on server.
Code Snippet
#Override
public void openCameraAction() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
imageBase64 = encodeToBase64(photo);
imageUri = getImageUri(getApplicationContext(), photo);
imageFile = new File(getRealPathFromURI(imageUri));
getImageView.setImageBitmap(photo);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),imageFile);
MultipartBody.Part image = MultipartBody.Part.createFormData(imageQuestionId, imageFile.getName(),requestBody);
parts.add(image);
}
}
public static String encodeToBase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Find a class image picker in this gist
https://gist.github.com/r00786/2c9aa88b706daccd55098ac2c28e7f39
all the things are handled in this class
How to use
private static final int PICK_IMAGE_ID = 234; // the number doesn't matter
public void onPickImage(View view) {
Intent chooseImageIntent = ImagePicker.getPickImageIntent(this);
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case PICK_IMAGE_ID:
Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
// TODO use bitmap
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
If you want the actual image taken camera to server u need to create
the image
Try this code
Delcare this Variable
private String actualPictureImagePath = "";
Then call this method on button click cameraIntent()
private void cameraIntent() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
actualPictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 1);
}
and Then in onActivityResult() handle this
#override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
File imgFile = new File(actualPictureImagePath);
if(imgFile.exists()){
InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(imgFile.getAbsolutePath());
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();
String base64String = output.toString();
}
}
}
This is the code to use for Bitmap to Base64
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm
is the bitmap object
byte[] byteArrayImage = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArrayImage,
Base64.DEFAULT);
NOTE:-
Do not forget to Add runtime permissions and in manifest also
1)Read and Write Persmission
2)Camera persmission

Take picture and convert to Base64

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.
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:
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...
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)
}
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;
}
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"

Increase image quality using Base64 string or other techniques

I'm playing with image uploading on android and the first method I encountered to do so is using the Base64 codification, however I noticed that the image quality is drastically lowered.
Do you have any suggestion or know other ways to upload an image to a MongoDB keeping a good quality?
Code I'm actually using:
public static String toBase64(Bitmap image) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
}
public static Bitmap fromBase64(String encodedImage) {
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
And here's what I use to capture the image:
private void captureImage() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
uploadImage(image);
}
}

How to convert photo taken by a camera into binary

I want to convert an image taken in phone's camera to binary and use that binary image for further processing. I made an app that will take the photo and save it in gallery.
How can I convert the photo it to binary?
Simple four lines for that:
Bitmap bmp = BitmapFactory.decodeFile("/imagepath/yourimage.jpg");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] b = bos.toByteArray();
Take image from camera using below method :
private void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("FROM CAMERA CLICKED file uri", fileUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_CODE_FROM_CAMERA);
}
After in onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == REQUEST_CODE_FROM_CAMERA
&& resultCode == Activity.RESULT_OK) {
try {
image_path = fileUri.getPath();
Bitmap bm = BitmapFactory.decodeFile(image_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}

Where to save an Image - android

I am developing Android application where users choose an icon image from a gallery. I need to save that image (bitmap), so I can use it when application is restarted.
Any simple example would be greatly appreciated.
Thanks.
Make use of the code below to save an image:
void saveImage() {
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
String fname = "Image.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();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Save");
alertDialog.setMessage("Your drawing had been saved:)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
And to retrive image from sdcard:
Supose you retrieves the image from sdcard in your Import.java Acitivty like that:
File file = new File(getExternalFilesDir(null), "MyFile.jpg");
So, once you have your image in a File object, you just need to put its path on a Intent that will be used to be a result data, which will be sent back to the "caller" activity. In some point of your "called" acitivity you should do that:
Intent resultData = new Intent();
resultData.putExtra("imagePath", file.getAbsolutePath());
setResult(RESULT_OK,returnIntent);
finish();
Your method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_OK)
{
String path = data.getStringExtra("imagePath");
}
}
That's it!
Hope it helps :)
http://developer.android.com/guide/topics/data/data-storage.html
I would suggest using external storage
Use SharedPreferences to store image in Base64 String representation.
Bitmap imageBitmap = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );
byte[] byte = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(byte , Base64.DEFAULT);
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences .edit();
sharedPreferencesEditor.putString("image_data", encodedImage).commit();
While retrieving, convert Base64 representation back to Bitmap.
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
String encodedImage = sharedPreferences.getString("image_data", "");
if( !encodedImage.equals("") ){
byte[] byte = Base64.decode(encodedImage , Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(byte, 0, byte.length);
imageView.setImageBitmap(bitmap);
}

Categories

Resources