Convert selected image into base64 string in Android (Java) - java

Button click to open camera, take picture and tried to convert that selected picture to base64 string but not working. please check below code.
private static final int CAMERA_PIC_REQUEST = 1337;
Button upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
upload = findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.uploadimage);
imageview.setImageBitmap(image);
String directoryPath = Environment.getExternalStorageDirectory() + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".png";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
System.out.print(filePath);
System.out.print(Uri.fromFile( new File(filePath) ));
File imageFile = new File(filePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image1 = stream.toByteArray();
String img_str = Base64.encodeToString(image1, 0);
}
I worked below code for convert static image into base64 string, but i want to take picture and convert to base64 string.
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.testimage);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.PNG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
System.out.print(ba1);

Please follow this to get actual image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
String imgString = toBase64(photo);
}
}
public String toBase64(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.NO_WRAP);
}

What I understand is, you need to do two things with the taken picture:
Show the picture in imageView.
Convert the picture to base64 String.
To do these two things, you don't need to write the Picture to file at your own code. You have already the bitmap from the camera using the following code:
Bitmap pictureFromCamera = (Bitmap) data.getExtras().get("data");
Now just show it in the imageView using
imageView.setImageBitmap(pictureFromCamera)
To convert it to base64, just convert the pictureFromCamera to base64 like
String base64StringOfCameraPic = getBase64StringFromBitmap(pictureFromCamera , 100)
String getBase64StringFromBitmap(Bitmap bitmap, int quality)
{
if (bitmap == null || quality < 0)
{
return null;
} else
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, quality, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}

Related

Storing image in SharedPreferences

mHomePage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
}
});
mHomePage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
CropImage.activity(resultUri)
.start(getActivity());
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();
}
Trying to store image in sharedpreference by encoding but I'm new to this and not able to figure it out. I saw some questions related to this problem but those aren't clear. Can someone help me out on how to store path/image in SharedPreferences?
Code isn't even compiling as I have put a uri in inout stream in .decodeStream().
The Uri points to the path where the image is stored, so first you would have to read it with InputStream.
This code will fix the compilation error. As a side-node, use edit.apply() instead of edit.commit().
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
try
{
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
//edit.commit();
edit.apply();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
However, I don't really see a point in storing an image in SharedPreferences? It's not really meant for that. Why don't you use save the file in context.getFilesDir() and read it from there when you need it? It's better than encoding/decoding it.

How to convert a captured Image or image selected from gallary to base64?

User can capture or select a image from gallery. I would like to upload that image to server.
This is my code for camera -
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//String encode = ImageBase64.encode(i);
startActivityForResult(i, CAMERA_REQUEST);
}
});
And this is my code to select a image from gallery -
gallary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent g = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(g, GALLARY_REQUEST);
}
});
Also, I am displaying that image with below code -
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
if(requestCode == CAMERA_REQUEST) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uploaded_img.setImageBitmap(bitmap);
}
}
if(requestCode == GALLARY_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
uploaded_img.setImageURI(uri);
}
}
Now, I would like to convert this image to base64 and upload to server.
Here you go:
public static String convertToBase64(String path) {
Bitmap bm = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String encodedImage = android.util.Base64.encodeToString(byteArrayImage, android.util.Base64.DEFAULT);
return encodedImage;
}
public static Bitmap decodeFromBase64ToBitmap(String encodedImage) {
byte[] decodedString = android.util.Base64.decode(encodedImage, android.util.Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
I've made it static in my project, so i don't have to create class instance.

how to send image taking by camera to server in actual size?

It Compresses in low quality but i want to send high quality image
bitmap = BitmapFactory.decodeFile(str);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] byte_v = stream.toByteArray();
if(bitmap!=null)
{
bitmap.recycle();
}
encod = Base64.encodeToString(byte_v,Base64.DEFAULT);
ImageMulti();
}
Set 100 insted of 40
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
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()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// Now use this bitmap to send to server
// Code to convert 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);
}
}
}
Alternate Solution for 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);
Alternate Solution
NOTE:-
Do not forget to Add runtime permissions and in manifest also
1)Read and Write Persmission
2)Camera persmission

Get base64 String from Image URI

I have content:// URI of an image and I want to convert it to base64. I don't know how to do this.
Here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Log.e("image", selectedfile.toString());
}
}
}
You can do it by using 2 steps.
1- URI to Bitmap conversion:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
}
}
}
2- Bitmap to Base64 String conversion:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
As a result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
//Use your Base64 String as you wish
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
}

Image String data send to the next activity

I select image from gallery and take image through camera.The code is following:
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
private static final int PICK_IMAGE = 150;
Uri imageUrl;
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestcode, int resultcode, Intent data) {
super.onActivityResult(requestcode, resultcode, data);
if (resultcode == RESULT_OK && requestcode == PICK_IMAGE) {
imageUrl = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUrl );
// Log.d(TAG, String.valueOf(bitmap));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
// im.setImageURI(imageUrl);
}
if (requestcode == CAMERA_REQUEST && resultcode == RESULT_OK) {
Bitmap photo;
photo = (Bitmap) data.getExtras().get("data");
im.setImageBitmap(photo);//set image to Imageview
}
}
Then trying to convert this image into base 64 string. The code is following:
private String imageToString(){
Bitmap photo = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then send the data to another activity. The code is following:
Intent next = new Intent(MainActivity.this, EventAdding.class);
Bundle bn = new Bundle();
bn.putString("image", imageToString());
startActivity(next);
The problem is that I am unable to synchronize all those program. The converting image string data don't send perfectly to the next activity.Image data don't send. when I was trying to show the image, a blank image is shown. Please, inform me the correct code
you can send image from one activity to other activity using the following code..
Bitmap bitmap = youimage
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("image", bitmap);
startActivity(intent);
now get the image in the secondActivity like this.
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("image");
Then display bitmap in ImageView.
You can use the intent.getParcelableExtra(key) method

Categories