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;
Related
I'm creating an android app where the user crops the image, the cropped image is shown and then has to be sent in the Result activity.
The problem I have is that when I send the image, it sends me the original uncropped image.
So I wonder, am I wrong something or the image is not really cropped?
Can anyone help me figure out how to display the cropped image in the Result activity?
Thank you so much for your help guys.
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
Crop method
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
show ImageCropped on MainActivity
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
full code MainActivity
private static final int PICK_IMAGE_GALLERY_REQUEST_CODE = 609;
public static final int ONLY_STORAGE_REQUEST_CODE = 613;
private String currentPhotoPath = "";
private UiHelper uiHelper = new UiHelper();
private ImageView imageView;
private Button vai;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vai = (Button)findViewById(R.id.button);
vai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vaiii();
}
});
findViewById(R.id.selectPictureButton).setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (uiHelper.checkSelfPermissions(this))
uiHelper.showImagePickerDialog(this, this);
});
imageView = findViewById(R.id.imageView);
}
private void vaiii() {
Intent i = new Intent(this, risult.class);
// your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
private void openImagesDocument() {
Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
pictureIntent.setType("image/*");
pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String[] mimeTypes = new String[]{"image/jpeg", "image/png"};
pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
startActivityForResult(Intent.createChooser(pictureIntent, "Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);
}
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
#Override
public void onOptionSelected(ImagePickerEnum imagePickerEnum) {
if (imagePickerEnum == ImagePickerEnum.FROM_GALLERY)
openImagesDocument();
}
private File getImageFile() throws IOException {
String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM
), "Camera"
);
System.out.println(storageDir.getAbsolutePath());
if (storageDir.exists())
System.out.println("File exists");
else
System.out.println("File not exists");
File file = File.createTempFile(
imageFileName, ".jpg", storageDir
);
currentPhotoPath = "file:" + file.getAbsolutePath();
return file;
}
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
}
Activity Result
if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent()
.getByteArrayExtra("byteArray").length);
star.setImageBitmap(b);
previewThumbnail.setImageBitmap(b);
}
I am trying to take a picture in Android using an Uri. But I am struggeling getting the bitmap from the created Uri. I always get a null-Object from my Uri.
Uri imgUri;
File newfile;
public static Button camButton;
public static ImageView img;
public static TextView text;
public void photo(Button cB, ImageView im, TextView tv) {
text = tv;
camButton = cB;
img = im;
camButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
String file = dir + "test" + ".png";
newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {
}
imgUri = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
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) {
Uri imageUri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", newfile);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (Exception e) {
e.printStackTrace();
}
bitmap = Bitmap.createBitmap(bitmap,0,((bitmap.getHeight()-bitmap.getWidth()))/2,bitmap.getWidth(),bitmap.getWidth());
bitmap = Bitmap.createScaledBitmap(bitmap, 64, 64, true);
img.setImageBitmap(bitmap);
}
}
I am getting the error Could not write image : java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
And as a result of this the bitmap cannot be loaded and my bitmap is null, so that i receive a NullpointerException
try with this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
Bitmap photo = null;
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
byte[] decodedString = Base64.decode(encoded, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
CircularImageView imageView = findViewById(R.id.profileimage);
imageView.setImageBitmap(decodedByte);
}
}
I have a problem when I'm trying to load a picture that saved on the phone.
I have a "Helper class"
public class FileHelper {
public static String saveBitmapToFile(Bitmap bitmap, Context context, String fileName) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// write the compressed bitmap to the outputStream(bytes)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
Toast.makeText(context, "בעיה ,", Toast.LENGTH_SHORT).show();
}
try {
fo.write(bytes.toByteArray());
fo.close();// close file output
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
Here's where I'm trying to upload the photo:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
iv = (ImageView) findViewById(R.id.ivPic);
btnTakePic = (Button) findViewById(R.id.btnpic);
btnPickPicture = (Button) findViewById(R.id.btnpicpic);
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
} catch (FileNotFoundException e) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);
}
iv.setImageBitmap(bitmap);
btnTakePic.setOnClickListener(this);
btnPickPicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = null;
if (v == btnTakePic) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
} else if (v == btnPickPicture) {
Intent pickPickIntent = new Intent(Intent.ACTION_PICK);
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String picDirPath = picDir.getPath();
Uri uData = Uri.parse(picDirPath);
pickPickIntent.setDataAndType(uData, "image/*");
startActivityForResult(pickPickIntent, PICK_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
{
bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
FileHelper.saveBitmapToFile(bitmap,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
} else if (requestCode == PICK_PICTURE) {
if (resultCode == RESULT_OK) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
options = new BitmapFactory.Options();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String ImageDecode = cursor.getString(columnIndex);
cursor.close();
options.inSampleSize = 5;
Bitmap bmp = BitmapFactory.decodeFile(ImageDecode, options);
iv.setImageBitmap(bmp);
FileHelper.saveBitmapToFile(bmp,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
}
}
}
and Here is where I am trying to load the saved pic:
private void updateHeader()
{
ImageView ivHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.ivHeader);
try{
bitmap= BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
ivHeader.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
Toast.makeText(getApplicationContext(),"error occured",Toast.LENGTH_LONG);
}
}
I have to say that the Toast message is not shown and There are no errors. App not crashing but the pic stays with no change.
Make sure you have external read storage permission. Here is how to request permission.
PS: Also make sure you have added that permission to AndroidManifest.xml
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();
}
}
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"