Take the picture from camera and decode it to base64 - android

I have built my webservice that will recieve the image decoded in base64
I have written this code that allowed me to take a picture from the camera and put it in an ImageView
I want to take this picture and convert it to a base64 String
Can anyone help doing this?
this is my code
class takepicActivity : AppCompatActivity() {
val CAMERA_REQUEST_CODE = 0
var pic:Bitmap?=null
var encoded_image:String?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_takepic)
val id = intent.getStringExtra("id")
//click on return
findViewById<TextView>(R.id.txt_return).setOnClickListener{
val intent = Intent(applicationContext, HelloActivity::class.java)
intent.putExtra("id",id)
startActivity(intent)
finish()
}
//take the pic
val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(callCameraIntent.resolveActivity(packageManager) != null)
startActivityForResult(callCameraIntent,CAMERA_REQUEST_CODE)
}
fun BitMapToString(bitmap: Bitmap): String {
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100,baos)
val b=baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
CAMERA_REQUEST_CODE -> {
if(resultCode == Activity.RESULT_OK && data != null){
pic_here.setImageBitmap(data.extras.get("data") as Bitmap)
}
else{val intent = Intent(applicationContext, HelloActivity::class.java)
startActivity(intent)
finish() }
}
else -> {Toast.makeText(this,"unrecognized request code", Toast.LENGTH_SHORT).show()}
}}
}

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;
}

In an old project, I've done the following :
public static String getEncodedFileContentBase64(final Context context, final Uri uri) {
String encoded = "";
if (context != null && uri != null) {
InputStream inputStream;
try {
String filePath = getRealPathFromURI(context, uri);
if (!TextUtils.isEmpty(filePath)) {
inputStream = BitmapUtils.getImageFile(filePath);
byte[] buffer = new byte[10 * ONE_KIO];
int bytesRead;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Base64OutputStream base64OutputStream = new Base64OutputStream(outputStream, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
base64OutputStream.write(buffer, 0, bytesRead);
}
base64OutputStream.close();
encoded = outputStream.toString();
}
} catch (Exception e) {
LogUtils.e(TAG, "Exception when reading image file: " + e.getMessage());
}
}
return encoded;
}
Hope it'll help you

Related

Image gets rotated automatically after uploading to firebase storage

I have an app which uploads user image into Firebase storage.
After Intent from the local, the image shows properly in the imageView, but after uploading to Firebase, it gets rotated to landscape.
This is the code I tried.
private void updatePhoto() {
if(resultUri != null) {
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (Exception e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = filePath.putBytes(data);
uploadTask.addOnFailureListener(e -> {
finish();
return;
});
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
uploadTask.addOnSuccessListener(taskSnapshot -> {
filePath.getDownloadUrl().addOnSuccessListener(uri -> {
Map newImage = new HashMap();
newImage.put("profileImage", uri.toString());
userDatabase.updateChildren(newImage);
progressDialog.dismiss();
finish();
});
return;
});
}else{
finish();
}
}
This is my onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mProfileImage.setImageURI(resultUri);
}
}
Here's Code to correct Image Position before Upload to Firebase
Check If Image need to rotation
private fun rotateImageIfRequired( context:Context, img:Bitmap, selectedImage:Uri):Bitmap {
// Detect rotation
var rotation = getRotation( context, selectedImage)
if (rotation != 0) {
var matrix:Matrix = Matrix()
matrix.postRotate(rotation as Float)
var rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true)
img.recycle()
return rotatedImg
}
else{
return img
}
}
Rotation Image
fun getRotation( context:Context, imageSelected: Uri):Int{
var rotation = 0
var content: ContentResolver = context.contentResolver
var arr:Array<String> = arrayOf("orientation","date_added")
val mediaCursor:Cursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arr,
null, null, "date_added desc")
if (mediaCursor != null && mediaCursor.getCount() != 0) {
while(mediaCursor.moveToNext()){
rotation = mediaCursor.getInt(0)
break
}
}
mediaCursor.close()
return rotation
}

Unable to convert pdf or docx file to base64 in 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();
}

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

Imageuploding on okhttp3 or Retrofit2, how can i get this uri?

I want to make service for imageuploading using retrofit2 or Okhttp3,
CODE :
public class GreenFragment extends Fragment {
#I omitted onCreateView that is for checking permission and trigger startGallry()
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
if(requestCode == 1000){
Uri returnUri = data.getData();
Bitmap bitmapImage = null;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
} catch (IOException e) {
e.printStackTrace();
}
mImageview.setImageBitmap(bitmapImage);
}
}
Uri returnUri;
returnUri = data.getData(); #This is what i want to control
}
#OnClick(R.id.btn_post)
public void onClick(View view) {
#Here is what i ask, How can i use retrunUri on here?
#On Android studio, retrunUri's font color is red, and not works.
Bitmap bitmap = getBitmapFromUri(returnUri);
File imageFile = createFileFromBitmap(bitmap);
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name", makeImageFileName() , RequestBody(MediaType.parse("image/png"), imageFile))
.build();
PostApiService.uploadFile(body);
}
# getBitmapFromUri(Uri uri) is for get Bitmap from uri, I omitted opts(options)
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getActivity().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap resizedBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);
parcelFileDescriptor.close();
return resizedBitmap;
}
#createFileFromBitmap(Bitmap bitmap) is for making File from Bitmap
private File createFileFromBitmap(Bitmap bitmap) throws IOException {
File newFile = new File(getActivity().getFilesDir(), makeImageFileName());
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.close();
return newFile;
}
#ImageFileName() is for setting filename
private String makeImageFileName() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss");
Date date = new Date();
String strDate = simpleDateFormat.format(date);
return strDate + ".png";
}
What I want to know is how to use returnUri which is from onActivityResult, in public void onClick(View view)?
I want to use returnUri in public void onClick(View view).
I used an example which is from youtube, but it's too hard for me to understand perfectly,
So please help me.
modify the onActiivtyResult then handle the Exception in OnClick
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
if(requestCode == 1000){
Uri returnUri = data.getData();
Bitmap bitmapImage = null;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
} catch (IOException e) {
e.printStackTrace();
}
mImageview.setImageBitmap(bitmapImage);
}
}
returnUri = data.getData(); //This is what i want to control
}
Uri returnUri;

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"

Categories

Resources