Converting image to string using the Base64 algorithm - android

I am new to android. I am trying to capture the image and store it in firebase. Since we need to convert the image to string and then store it in firebase, I am using the base64 algorithm.
The methods for capturing image and storing it in the database is :
public void capturePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(photo);
}
}
public void storeDatabase(View v)
{
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRollno.getText().toString());
ref1.child("Marks").setValue(editmarks.getText().toString());
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
n++;
}
When I click on the submit button, it takes a lot of time to upload the values. Moreover, many a times I can see the line
Skipped 537 frames! The application may be doing too much work on its main thread.
in the Android Monitor.
If I comment the image processing lines, it is working all fine.
Can somebody please tell me how to avoid such error so that the image is uploaded instantly in my database.

For storing it to the database, I would definitely use AsyncTask for this one. So, what you could have is a separate class that does the following:
private class ImageDBManager extends AsyncTask< String, Integer, Void> {
protected Long doInBackground(String... items) {
int count = items.length;
String editRoll = items[0];
String editName = items[1];
String editMarks = items[2];
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRoll);
ref1.child("Marks").setValue(editName);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(){
}
}
And then call it like this:
public void storeDatabase(View v) {
ImageDBManager manager = new ImageDBManager();
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
manager.execute(new String[] { editRollno.getText(), editname.getText(), editmarks.getText() }
}
If you are capturing the image from the camera, the best reference is here
http://developer.android.com/training/camera/photobasics.html
it's the same idea of starting an activity and implementing onActivityForResult where you get the data from the extras in the result, so instead of getting the bitmap from the R.drawable.abc, you'd get it like this in onActivityForResult
Bitmap imageBitmap = (Bitmap) extras.get("data");

Related

Capture image from camera return low quality image

I've been developed app to take a picture to be saved in gallery. I've searched online and the easiest way that I could practice was to use data.getExtras().get("data") . So below are the code to take picture from camera. Note that I'm using fragment in this class.
img22a1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_01);
}
});
Get the captured image and convert it to string
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_01) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
((SiteProgress) getActivity().getApplication()).seti22a1(Base64.encodeToString(byte_arr, Base64.DEFAULT));
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
img22a1.setBackgroundDrawable(ob);
} else if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
I save the string into global variable so another activity can access it.
In another activity, I have a button to save the image into folder/gallery by accessing the image string.
for(int i=0;i<=namefile.length;i++){
Bitmap[] bitmap = new Bitmap[namefile.length];
FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());
}
It worked to save the image into folder/gallery....But the quality of image was very low...I could barely see text in the image.
They said data.getExtras().get("data") supposed to return thumbnail and not the actual image. What I want here is to get the full image and not the thumbnail one.
Any answer will be very appreciated.
From: Android - How to get the image using Intent data
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println(String.format("Bitmap(CAMERA_IMAGES_REQUEST): %s", thumbnail));
System.out.println(String.format("cap_image(CAMERA_IMAGES_REQUEST): %s", cap_image));
cap_image.setImageBitmap(thumbnail);
}

Android || How to parse the Image from one activity to another?

This is my code. I want to add one more button here which onclick send the image to next activity , but I am not able to configure this. How should I do it?
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// 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);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Initially, keep newly added button disable and in onActivityResult method after getting image string enable button and set onClickListener to button. And pass that image string to next activity using intent extra.
In onActivityResult method,
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),NextActivity.class).putExtra("img",imgDecodableString));
}
});
Best way to do this with large image would be using Serializable, since Intent and Parcelable both have size limit.
Answers to this question might help : Serializing and De-Serializing android.graphics.Bitmap in Java
you can put the data in your first activity like
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and in second activity parse the data like below:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
convert your imagepath to bitmap code snipped is:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
//First Activity
Bitmap b = null;
String bitmapString = getStringFromBitmap(b);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bitmapString", bitmapString);
//Second Activity
String receivedBitmapString = getIntent().getStringExtra("bitmapString");
Bitmap receivedBitmap = getBitmapFromString(receivedBitmapString);
//Functions
private String getStringFromBitmap(Bitmap bitmapPicture) {
/*
* This functions converts Bitmap picture to a string which can be
* JSONified.
* */
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
private Bitmap getBitmapFromString(String jsonString) {
/*
* This Function converts the String back to Bitmap
* */
byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
Source:Link

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"

How to save Image in shared preference in Android | Shared preference issue in Android with Image

In my application after login I have to save user name and image in shared preference for other pages. I am able to save name in preference but can't get any where how to save image.
I am trying something like that-
SharedPreferences myPrefrence;
String namePreferance="name";
String imagePreferance="image";
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", itemImagePreferance);
editor.commit();
I am trying to save image as string after convert it into object. But when I reconvert it into bitmap I did not get anything.
I solved your problem do something like that:
Write Method to encode your bitmap into string base64-
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
Pass your bitmap inside this method like something in your preference:
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeTobase64(yourbitmap));
editor.commit();
And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Please pass your string inside this method and do what you want.
Finally I solved this problem.
Step:-
1. I wrote some code in onCreate() for get intent data from previous Activity
private Bitmap bitmap;
Intent intent = getIntent();
if (getIntent().getExtras() != null)
{
// for get data from intent
bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");
// for set this picture to imageview
your_imageView.setImageBitmap(bitmap);
sharedPreferences();
}else
{
retrivesharedPreferences();
}
2 create sharedPreferences() and put this code
private void sharedPreferences()
{
SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
editor.commit();
}
3 create retrivesharedPreferences() this method and put this code,
private void retrivesharedPreferences()
{
SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
String photo = shared.getString("PRODUCT_PHOTO", "photo");
assert photo != null;
if(!photo.equals("photo"))
{
byte[] b = Base64.decode(photo, Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
bitmap = BitmapFactory.decodeStream(is);
your_imageview.setImageBitmap(bitmap);
}
}
4 Write encodeTobase64() Method to encode your bitmap into string base64- and put code in this method
public static String encodeTobase64(Bitmap image) {
Bitmap bitmap_image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
I hope it will helpful for you.
Encode to Base64?! That's crazy talk! That's way too much information that you are storing to the shared preferences. The strategy you should be doing is saving the Image URI file path, and retrieving it as such. This way, your app won't be storing so much information and become a memory hog when decoding the image.
I made a simple App on Github to demonstrate this idea, if you want to follow:
1. Declare the variables:
private ImageView mImage;
private Uri mImageUri;
2. Select the image:
public void imageSelect() {
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_REQUEST);
}
3. Save the image URI:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_IMAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a image.
// The Intent's data Uri identifies which item was selected.
if (data != null) {
// This is the key line item, URI specifies the name of the data
mImageUri = data.getData();
// Removes Uri Permission so that when you restart the device, it will be allowed to reload.
this.grantUriPermission(this.getPackageName(), mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
this.getContentResolver().takePersistableUriPermission(mImageUri, takeFlags);
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
mImage.setImageURI(mImageUri);
mImage.invalidate();
}
}
}
}
4. Retrieve the image URI when needed:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mImageUri = preferences.getString("image", null);
mImage.setImageURI(Uri.parse(mImageUri));
That's it! Now we have saved the image uri path to shared preferences cleanly, and have not wasted valuable system resources encoding the image and saving it to SharedPreferences.
//Thanks Maish srivastava
// i will do complete code just copy past and run it sure worked it
//
public class MainActivity extends Activity implements OnClickListener
{
private static int RESULT_LOAD_IMAGE = 1;
public static final String MyPREFERENCES = "MyPre" ;//file name
public static final String key = "nameKey";
SharedPreferences sharedpreferences ;
Bitmap btmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(key))
{
String u=sharedpreferences.getString(key, "");
btmap=decodeBase64(u);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(btmap);
}
ImageButton imgbtn=(ImageButton) findViewById(R.id.imageButton1);
imgbtn.setOnClickListener(this);
}
public void onClick(View v)
{
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.imageButton1:
try
{ //go to image library and pick the image
Intent i=newIntent(ntent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
#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();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
btmap=BitmapFactory.decodeFile(picturePath);//decode method called
Editor editor = sharedpreferences.edit();
editor.putString(key, encodeTobase64(btmap));
editor.commit();
}
}
public static String encodeTobase64(Bitmap image)
{
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

How to save an image from an ImageView after taking a picture

I am picking the picture from gallery or taking it with the camera.
If I get the picture into my imageView, and click the confirm button, how can I then save that picture?
Do I have to use saveState()?
Please post some comments.
Thanks.
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 80, 80, false);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
mImageView.setImageURI(selectedImageUri);
break;
}
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
ImageView image = (ImageView) mImageView.setImageURI(); //how to edit?
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date);
}
}
//How can I save image after clicking button?
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
setResult(RESULT_OK);
finish();
}
});
You can save the image of all View (not only ImageView) following these steps:
1.Get the bitmap of your view:
public Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
v.invalidate();
return b;
}
2.Save it on your SD card file (or wherever you want):
protected String saveBitmap(Bitmap bm, String name) throws Exception {
String tempFilePath = Environment.getExternalStorageDirectory() + "/"
+ getPackageName() + "/" + name + ".jpg";
File tempFile = new File(tempFilePath);
if (!tempFile.exists()) {
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
}
tempFile.delete();
tempFile.createNewFile();
int quality = 100;
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bm.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
bm.recycle();
return tempFilePath;
}
These code take from one of my project, but I think they are easy to understand and re-use. Hope it will help you.
I'm not sure how to do this from the gallery or why you would want to since the image is already saved to the phone if it is in the gallery. You should be able to re-write the file using the file's URI though.
If you are taking the image with the camera, you can see that you have a Bitmap of the image. It should be relatively easy to save it using the following snippet of code:
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
You will want the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For more information, try following this example (it is where I found the code snippets). They are uploading their image but the same concepts should apply.
http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html
Hope this helps!

Categories

Resources