Store image location after cropping into the app folder in android - android

I have an activity in which when a user clicks the ImageView a dialog appears and he can choose pick from gallery or camera. I was a success in writing all the code and was able to replace the ImageView with the new image. I have converted the image in base64 and stored the image in shared preference. Is there is any way to store the image location after cropping in the shared preference I have added my code here? Thank you in Advance
Profile_Activity.java
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Profile_Activity extends AppCompatActivity {
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
final String[] items = new String[]{"Take From Camera", "Select From Gallery"};
ImageView picture;
AlertDialog.Builder builder;
ArrayAdapter<String> adapter;
private AccountManager mAccountManager;
private int PICK_IMAGE_REQUEST = 1;
private SharedPreferences mPreferences, myPrefs;
private SharedPreferences.Editor myPrefsEdit;
private Uri mImageCaptureUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
builder = new AlertDialog.Builder(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Profile");
}
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
myPrefsEdit = myPrefs.edit();
picture = (ImageView) findViewById(R.id.picture);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
//END CAMERA STUFF
}// End OnCreate
});
String temp = myPrefs.getString("url", "defaultString");
try {
byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
myPrefsEdit.putString("url", temp);
myPrefsEdit.commit();
picture.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size != 0) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}

Related

Camera is giving very big size image on device

In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}

How to select an image from the gallery and convert it to Base64? [duplicate]

sorry for asking silly question.but it solved yet my me.please help i had tried all codes on stackoverflow and follow other tutorial but it wont help at all.i am taking image from galary and convert to base64 it works perfectly fine when taking image on camera but why it dont work on galary i dont know please help me.;(
This is the code to select the image
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(TestFragment.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= Utility.checkPermission(TestFragment.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
After this
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//perfectly string base64 to image
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//checking in log base64 string to image cropeed image found
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void showToastMessage(String message) {
Log.v(TAG, String.format("showToastMessage :: message = %s", message));
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
why i found the cropped image after selecting from galary?there is no error in error log here is the logcat
E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/
W/FlurryAgent: Flurry session paused for
1 and remote module com.google.android.gms.tagmanager:8
Selected remote version of com.google.android.gms.tagmanager, version >= 8
No container asset found in /assets/containers. Checking top level /assets directory for container assets.
Tag Manager's event handler WILL NOT be installed (no container loaded)
Tag Manager initilization took 274ms
Using measurement service
Connecting to remote service
Connected to remote service
Processing queued up service tasks: 1
Suspending all threads took: 25.809ms
V/help: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAzABywDASIA
AhEBAxEB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GsiZ6M3JY+nr9aLhZIE2sBscHbgYB96ZNFKroU
f92zAccE47USpNKrAjB/2hgA9v8A9YrGXWz3LirO6GCfklwOBwB0BqL7M8agSoVZ/m3ZyMe3tTJI
ZGbAIDr1BPB/xqWRXKNuXK8cdzWHLrobRtEjhHyoHIV1Odw5B/8A1U2VpJI9y4KE9Scfj709JUUc
qE3c7fSmy7ZI2LP+742oB90+3fn3rFxfM77aGyd1oVfUAhj7cCpbYSNEysQrHjaOlQyKA4K5XA65
71NCrLHuZg4PTAwa0aTVirkDWmVZWwyk4YDgH0qSG1YMwABXgjB5pFkjZ2bac9xg4/z704XRi3Lg
IHGBnr/k09e5LaW4pzIiZGfLGBzyoJpl45KZTBxwPQU2FzudASQuC2Rz7Zp5k3KQRhuoI5x+Hf61
SbWotCrAgU9CWYjdj09frUj7SxC8gc5PAxTgSyZiwc8ZHYd+aTeEZ14IYck9DU66u5peysRhQ4Ib
DEEEsOBSM6BgYyCoHDDpT/3bxN8uQOoPQ/UVHDEuWAOGPTA6UyGk9GPExAJRNzEjO
You can use following code:
public static String encodeTobase64(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Use below code in onActivityResult()
InputStream imageStream = null;
try {
imageStream = this.getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
encodeTobase64(yourSelectedImage);
Try this...
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Here is a similar code. I have implemented the same thing in my app. You can select images from either gallery or camera and You can convert it as a base 64. Try this Its working for me. Hope it work for you too
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import in.invis.organickerala.utilities.CropOption;
import in.invis.organickerala.R;
public class Profile_Activity extends AppCompatActivity {
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
final String[] items = new String[]{"Take From Camera", "Select From Gallery"};
ImageView picture;
AlertDialog.Builder builder;
ArrayAdapter<String> adapter;
private AccountManager mAccountManager;
private int PICK_IMAGE_REQUEST = 1;
private SharedPreferences mPreferences, myPrefs;
private SharedPreferences.Editor myPrefsEdit;
private Uri mImageCaptureUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
builder = new AlertDialog.Builder(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Profile");
}
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
myPrefsEdit = myPrefs.edit();
picture = (ImageView) findViewById(R.id.picture);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
//END CAMERA STUFF
}// End OnCreate
});
String temp = myPrefs.getString("url", "defaultString");
try {
byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
myPrefsEdit.putString("url", temp);
myPrefsEdit.commit();
picture.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("Image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find Image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size != 0) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
This is how I do it on my onActivityResult of my gallery intent.
String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());
Then converting the whole thing to bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Here is my getRealPathFromURI method from ImageUtil Class.
public static String getRealPathFromURI(Context context, Uri contentURI) {
String result = null;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
result = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
And here is my conversion from bitmap to base64.
public static String getBase64(Bitmap bitmap) {
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
return null;
}

calling another class functions from one class on button click in android

I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.
This is my main class:-
package com.example.ishan.complainbox;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;
public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// Get References of Views
str = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pn = (EditText) findViewById(R.id.pin);
det = (EditText) findViewById(R.id.detail);
save = (Button) findViewById(R.id.save);
pic=(Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
}
public void onClick(View view) {
String street = str.getText().toString();
String cty = city.getText().toString();
String pin = pn.getText().toString();
String detail = det.getText().toString();
// check if any of the fields are vaccant
if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both passwords match
else
{
// Save the Data in Database
dbHandler.insertEntry(street,cty,pin,detail);
Toast.makeText(getApplicationContext(), "Complaint Successfully
Filed ", Toast.LENGTH_LONG).show();
}
}
};
.....and this is the camera class..:-
package com.example.ishan.complainbox;
/**
* Created by ishan on 13/04/2017.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class camera extends MainActivity{
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
btnSelect = (Button) findViewById(R.id.uploadpic);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.imgView);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED)
{
if(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(camera.this);
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() +
".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap(getApplicationContext().
getContentResolver(),
data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
}
This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html
EDIT
Response to OP's question in comment-
You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture

Take image from gallery and convert to base64 issue

sorry for asking silly question.but it solved yet my me.please help i had tried all codes on stackoverflow and follow other tutorial but it wont help at all.i am taking image from galary and convert to base64 it works perfectly fine when taking image on camera but why it dont work on galary i dont know please help me.;(
This is the code to select the image
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(TestFragment.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= Utility.checkPermission(TestFragment.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
After this
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//perfectly string base64 to image
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//checking in log base64 string to image cropeed image found
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void showToastMessage(String message) {
Log.v(TAG, String.format("showToastMessage :: message = %s", message));
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
why i found the cropped image after selecting from galary?there is no error in error log here is the logcat
E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/
W/FlurryAgent: Flurry session paused for
1 and remote module com.google.android.gms.tagmanager:8
Selected remote version of com.google.android.gms.tagmanager, version >= 8
No container asset found in /assets/containers. Checking top level /assets directory for container assets.
Tag Manager's event handler WILL NOT be installed (no container loaded)
Tag Manager initilization took 274ms
Using measurement service
Connecting to remote service
Connected to remote service
Processing queued up service tasks: 1
Suspending all threads took: 25.809ms
V/help: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAzABywDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8v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wa0aTVirkDWmVZWwyk4YDgH0qSG1YMwABXgjB5pFkjZ2bac9xg4/z704XRi3Lg
IHGBnr/k09e5LaW4pzIiZGfLGBzyoJpl45KZTBxwPQU2FzudASQuC2Rz7Zp5k3KQRhuoI5x+Hf61
SbWotCrAgU9CWYjdj09frUj7SxC8gc5PAxTgSyZiwc8ZHYd+aTeEZ14IYck9DU66u5peysRhQ4Ib
DEEEsOBSM6BgYyCoHDDpT/3bxN8uQOoPQ/UVHDEuWAOGPTA6UyGk9GPExAJRNzEjO
You can use following code:
public static String encodeTobase64(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Use below code in onActivityResult()
InputStream imageStream = null;
try {
imageStream = this.getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
encodeTobase64(yourSelectedImage);
Try this...
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Here is a similar code. I have implemented the same thing in my app. You can select images from either gallery or camera and You can convert it as a base 64. Try this Its working for me. Hope it work for you too
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import in.invis.organickerala.utilities.CropOption;
import in.invis.organickerala.R;
public class Profile_Activity extends AppCompatActivity {
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
final String[] items = new String[]{"Take From Camera", "Select From Gallery"};
ImageView picture;
AlertDialog.Builder builder;
ArrayAdapter<String> adapter;
private AccountManager mAccountManager;
private int PICK_IMAGE_REQUEST = 1;
private SharedPreferences mPreferences, myPrefs;
private SharedPreferences.Editor myPrefsEdit;
private Uri mImageCaptureUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
builder = new AlertDialog.Builder(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Profile");
}
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
myPrefsEdit = myPrefs.edit();
picture = (ImageView) findViewById(R.id.picture);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
//END CAMERA STUFF
}// End OnCreate
});
String temp = myPrefs.getString("url", "defaultString");
try {
byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
myPrefsEdit.putString("url", temp);
myPrefsEdit.commit();
picture.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("Image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find Image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size != 0) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
This is how I do it on my onActivityResult of my gallery intent.
String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());
Then converting the whole thing to bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Here is my getRealPathFromURI method from ImageUtil Class.
public static String getRealPathFromURI(Context context, Uri contentURI) {
String result = null;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
result = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
And here is my conversion from bitmap to base64.
public static String getBase64(Bitmap bitmap) {
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
return null;
}

Problems when loading cameraimages in imageView

When I take a picture, the picture will saved on the SD.(This works very well)
But the picture won´t shows in the imageView. Do you have any idea?
package de.example.Camera;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Cam extends Activity {
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_cam);
Button button2 = (Button) findViewById(R.id.photo);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start ActivityTwo
/*
* Intent intent = new Intent(getApplicationContext(),
* ActivityTwo.class); intent.putExtra("MyStringValue",
* editText1.getText().toString()); startActivity(intent);
*/
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
}else {
// The picture was returned
Bundle extras = intent.getExtras();
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
private Uri getOutputMediaFile() throws IOException {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DayTwentyNine");
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
if (mediaFile.exists() == false) {
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
}
return Uri.fromFile(mediaFile);
}
}
In the manifest I have are the following:
uses-feature android:name="android.hardware.camera" android:required="false"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here I have this peace of code that works fine the first function open the camera and take the picture and the second one place the image you took into an image view...
public void takePictu(View view) {
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){
photo3 = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo3);
imageView.buildDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo3.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
}

Categories

Resources