Android convert Bitmap to Base64 string issue - android

i have a problem with converting Bitmap to Base64. I want to post some images from camera or gallery. When i get them as image and i must convert to base64 but when i'm getting the string and testing with http://codebeautify.org/base64-to-image-converter to see my image. Result looks very bad quality. How can i fix this pls help me ?
Here is my code:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode)
{
case 0:
if(resultCode == RESULT_OK)
{
Bundle extras = imageReturnedIntent.getExtras();
Bitmap selectedImage = (Bitmap)extras.get("data");
secilenImage.setImageBitmap(selectedImage);
String encodedImage;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try
{
selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] b = stream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
images.add(i, encodedImage);
Log.d("StringForCamera: ", encodedImage);
stream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
secilenImage.setImageBitmap(selectedImage);
secilenImage.setEnabled(false);
}
break;
case 1:
if(resultCode == RESULT_OK)
{
Uri imageUri = imageReturnedIntent.getData();
Bitmap selectedImage = null;
String encodedImage;
try
{
selectedImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.NO_WRAP);
images.add(i, encodedImage);
Log.d("StringForGallery: ",encodedImage);
}
catch(IOException e)
{
e.printStackTrace();
}
secilenImage.setImageBitmap(selectedImage);
secilenImage.setEnabled(false);
}
break;
}
++i;
}

(Bitmap)extras.get("data");
That is only a thumbnail of the image. Hence the low quality.

Related

I need to use a bitmap image but i dont know how

Im trying to change the google maps marker in a Android application, I tried this way:
mMap.addMarker(new MarkerOptions().position(player).title("player").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher_foreground)));
but it says that I have to use a bitmap image, what should I do?
FATAL EXCEPTION: main Process: com.example.crosilla.mappeprova2, PID: 18930
com.google.maps.api.android.lib6.common.apiexception.b: Failed to decode image. The provided image must be a Bitmap
Your code looks ok. Try with a resource from the mipmap folder.
call this on button click:
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
then :
#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) {
dialog = new ProgressDialog(PhotoUpload.this);
dialog.setMessage("Please wait......");
dialog.setCancelable(false);
dialog.show();
Uri selectedImage = data.getData();
SharedPreferences sharedPreferences = getSharedPreferences("SavedPhoto", Context.MODE_PRIVATE);
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(encodedImage , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
CircularImageView imageView = findViewById(R.id.profileimage);
imageView.setImageBitmap(decodedByte);
}
}

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

Bad photo quality captured from camera or gallery

I have a problem in my app:
i must get photo from camera or gallery, show it in a small imageView and sent it to server in base64 format (i don't need save image as file in the phone).
i can take photo but with very bad quality!
The solutions found in internet don't work for me
Can you help me?
here is the code
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
bitmap_photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap_photo,
70, 70, true);
userImage.setImageBitmap(newBitmap);
bitmap_photo = newBitmap;
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
userImage.setImageURI(selectedImage);
try {
bitmap_photo = MediaStore.Images.Media.getBitmap(this.getContentResolver(),selectedImage);
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap_photo,
70, 70, true);
bitmap_photo = newBitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
and this is the code to convert image to base64:
public String getBase64Image(){
if(bitmap_photo!=null){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap_photo.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String base64image = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return base64image;
} else {
return "";
}
}
thank you!

Portrait Camera Images when Uploaded via Library rotates in ImageView Android

In my Android App, I have an option where a user can take his photograph or upload an image from his Gallery at the time of registration. This image, once successfully taken by camera or selected from Gallery, is shown in an ImageView. Below is the onClick of ImageView code that starts this process.
This is from Activity Layout.
<ImageView
android:id="#+id/imgUserImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:onClick="changePicture"
app:srcCompat="#drawable/profile_image_not_provided"
android:layout_below="#+id/textView2"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp" />
This is from Activity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have managed to get the Orientations properly. Now the problem is, how should I rotate the image before imgProfilePicture.setImageURI(selectedImage);.
I managed to find the solution. Please feel free to post a better solution, if you think this can be improvised.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
//Starting from here, I am checking the Orientation and storing the result in orientation variable.
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
//This is the end of Orientation Check.
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
//Based on the Orientation Check result, I rotate the ImageView Image to make it straight.
if (orientation == 270) {
imgProfilePicture.setRotation(-90);
} else if (orientation == 0) {
imgProfilePicture.setRotation(0);
}
//This is the end of Image Rotation based on the Orientation Check Result.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Data not return from Google Photo Intent android

I have been trying to load an image from Google Photos App into my application. When I choose an image in Google Photos, my application crashes, but if I select the image from the Gallery App, it works. Please what am I missing out? Find my code below.
itemImage.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
public void pickImage() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.putExtra("crop", "true");
galleryIntent.putExtra("outputX", 100);
galleryIntent.putExtra("outputY", 100);
galleryIntent.putExtra("scale", true);
galleryIntent.putExtra("return-data", true);
// Start the Intent
startActivityForResult(galleryIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
//Uri uri = data.getData();
Bitmap bmp = (Bitmap) data.getExtras().get("data");
itemImage.setImageBitmap(bmp);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
} catch (Exception e){}
}
}
I have tweaked the code a little bit. Now I can import all images on the Gallery and Photos app except for camera images. See my new code below:
public void pickImage() {
// Create intent to Open Image applications like Gallery, Google Photos
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
//Uri uri = data.getData();
final Uri uri = data.getData();
final InputStream imageStream = getActivity().getContentResolver().openInputStream(uri);
final Bitmap bmp = BitmapFactory.decodeStream(imageStream);
itemImage.setImageBitmap(bmp);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
/*bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);*/
} catch (Exception e){}
}
}

Categories

Resources