Android picture saved to internal storage is the thumbnail - android

I made a class to take and save pictures to internal storage, but the the problem is i save thumbnail and not full sized photo.
This is the class :
public class PhotoManager {
private final static String DEBUG_TAG = "PHOTOMANAGER";
private String mCurrentPhotoPath = "";
private String filePath = "";
private Intent takePictureIntent;
private Activity activity;
private String type;
private int Q_ID;
private PhotoCallbackListener mListener;
private FragmentManager fragManager;
public void setListener(PhotoCallbackListener listener) {
mListener = listener;
}
public PhotoManager(Activity activity, int Q_ID, String type, FragmentManager fm, PhotoCallbackListener listener) {
this.activity = activity;
this.Q_ID = Q_ID;
this.type = type;
this.mListener = listener;
this.fragManager = fm;
}
// init la vue de la camera
public void init(){
dispatchTakePictureIntent(11);
}
// affiche la camera
private void dispatchTakePictureIntent(final int actionCode) {
Fragment f = new Fragment() {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (data != null) {
try {
handleSmallCameraPhoto(data);
} catch (IOException e) {
e.printStackTrace();
}
// efface la photo créee de la galerie
activity.getContentResolver().delete(data.getData(), null, null);
}
}
};
FragmentTransaction fragmentTransaction = this.fragManager
.beginTransaction();
fragmentTransaction.add(f, "getpicture");
fragmentTransaction.commit();
}
private void handleSmallCameraPhoto(Intent intent) throws IOException {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
filePath = saveToInternalStorage(mImageBitmap);
galleryAddPic();
mListener.callback(mImageBitmap, filePath);
}
private File createImageFile() throws IOException {
// Create an image file name
Log.d(DEBUG_TAG,"createImageFile");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0));
String imageFileName = timeStamp + "_";
File image = File.createTempFile(
imageFileName,
".jpg",
null //default location for temporary files
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.d(DEBUG_TAG,"return "+image.getAbsolutePath());
return image;
}
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(activity.getApplicationContext());
Log.d(DEBUG_TAG,"saveToInternalStorage");
File directory = cw.getDir("imageDir_"+type, Context.MODE_PRIVATE);
String fileName = "q"+Q_ID+".jpg";
// Create imageDir
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(DEBUG_TAG,"return "+directory.getAbsolutePath());
return directory.getAbsolutePath();
}
private void galleryAddPic() {
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
activity.sendBroadcast(mediaScanIntent);
}
}
I use it like this :
pm = new PhotoManager(getActivity(), Q_ID, getArguments().getString("type"), fm, new PhotoCallbackListener() {
#Override
public void callback(Bitmap mImageBitmap, String file) {
imagePreview.setImageBitmap(mImageBitmap);
filePath = file;
}
});
Button buttonPhoto = (Button) view.findViewById(R.id.q4BtnPhoto);
buttonPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pm.init();
}
});
I return the bitmap thumbnail to put it in the layout, and the filePath just for test.
Can anyone help me to understand why the full sized photo is not saved ?
Thanks !

Solved by myself :
I made a big mistake, i saved the thumbnail to internal storage not the full sized.
in the method handleSmallCameraPhoto i can get the full sized saved image with :
Uri fullsizeImage = intent.getData();
I get the bitmap of the image like this :
Bitmap mBitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), fullsizeImage);
Then after i call my saveToInternalStorage method.

Related

Android File Not Found Exception, though the image is saved

I am making an app which utilizes the camera, and has the ability to take a picture to use a simple image recognition API on it. I can use the gallery just fine to upload images, but straight from the camera is giving me massive issues. I have basically just copied the android dev documentation for most of the image creation, though may have needed to change some items here and there.
Here is the total code:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + "Image_for_Stack" + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = "file: " + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.v(TAG, "IO Exception " + ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(getContextOfApplication(),
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, IMAGE_CAPTURE);
}
}
} catch (Exception e) {
Log.v(TAG, "Exception in dispatch " + e);
}
}
private void galleryAddPic() {
try {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getContextOfApplication().sendBroadcast(mediaScanIntent);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
}
And in a separate class, this is called:
public static byte[] getByteArrayFromIntentData(#NonNull Context context, #NonNull Intent data) {
InputStream inStream = null;
Bitmap bitmap = null;
try {
inStream = context.getContentResolver().openInputStream(data.getData());
Log.v(TAG, "Instream works");
bitmap = BitmapFactory.decodeStream(inStream);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
return outStream.toByteArray();
} catch (FileNotFoundException e) {
Log.v("FileOP Debug", "Exception " + e);
return null;
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException ignored) {
}
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
Now, the image is created without issue. I can go to the emulator, look through the photo's app, and get:
.
However, I get this error when the code gets to giving inStream a value:
java.io.FileNotFoundException: /file:
/storage/emulated/0/DCIM/Camera/JPEG_Image_for_Stack_3248071614992872091.jpg
(No such file or directory) .
I don't exactly understand how this could be. The item clearly exists, and is saved on the phone. The app does request and is given the permission to write to external storage, and I have checked in the emulator permissions that it is given. Write also comes with read, so that shouldn't be an issue as far as I'm aware either.
Edit
To show where this code is being called from.
else if (requestCode == IMAGE_CAPTURE) {
galleryAddPic();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
final ProgressDialog progress = new ProgressDialog(getContextOfApplication());
progress.setTitle("Loading");
progress.setMessage("Identify your flower..");
progress.setCancelable(false);
progress.show();
if (!CheckNetworkConnection.isInternetAvailable(getContextOfApplication())) {
progress.dismiss();
Toast.makeText(getContextOfApplication(),
"Internet connection unavailable.",
Toast.LENGTH_SHORT).show();
return;
}
client = ClarifaiClientGenerator.generate(API_KEY);
final byte[] imageBytes = FileOp.getByteArrayFromIntentData(getContextOfApplication(), mediaScanIntent);
As of right now, imageBytes will be null as the the FileNotFound exception is thrown on that method call.
You can try this code...
public class Images extends Activity
{
private Uri[] mUrls;
String[] mFiles=null;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.images);
File images = Environment.getDataDirectory();
File[] imagelist = images.listFiles(new FilenameFilter(){
#override
public boolean accept(File dir, String name)
{
return ((name.endsWith(".jpg"))||(name.endsWith(".png"))
}
});
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setFadingEdgeLength(40);
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(260, 210));
return i;
}
private Context mContext;
}
}

how can i store gallery image in application directory

i have got the image directly from the camera , gallery to the image view in my app its all working fine.
Now what I want is to save this image from Image View to the application directory and also access it when required.
//You Can try This
File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/yourDirectoryname");
myDir.mkdirs();
File file = new File(myDir, yourImagePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
public class EditProfile extends AppCompatActivity {
ImageView imageView;
EditText Name,Email,MobileNo;
public static int count = 0;
String loginid;
Bitmap bitmap;
private static final int CAMERA_REQUEST = 1888;
String picturePath;
static int i=0;
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
byte[] image = null;
Button button1;
static File out;
String path1;
ImageView imageView1;
Bitmap photo ;
byte[] b=null;
Button EditProfile;
String Username;
String name;
String email;
String Imgpath;
String Imgpath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
EditProfile=(Button)findViewById(R.id.edit_profile);
Imgpath=getSharedPreferences("Bytearray",0).getString("Bytearray",null);
Imgpath1=getSharedPreferences("uri",0).getString("uri",null);
imageView=(ImageView)findViewById(R.id.profile_photo);
EditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
String path=out.getAbsolutePath();
getSharedPreferences("path",0).edit().putString("path",path).commit();
imageView.setImageBitmap(mBitmap);
}
else if (requestCode == 2) {
imageView.setImageURI(selectedImage);
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 filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// imageView.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap image=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
imageView.setImageBitmap(image);
}
}
}
Initiate the camera intent like this by creating a file of known path,and after the image capture Your image appears in that path:
Uri capturedImageUri;//global variable
private void initiateImageCapture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
capturedImageUri = Uri.fromFile(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile == null || capturedImageUri == null) {
Utils.showLongToast(getActivity(), "error");
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
startActivityForResult(takePictureIntent, Constants.INTENT_IMAGE_CAPTURE);
else
Utils.showLongToast(getActivity(), "try again);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}

Start new activity after having taken a picture with Android camera

I'm using Google PhotoIntentActivity sample to implement the native Android camera in my app.
In this sample you click a button from the main activity (called PhotoIntentActivity), the camera is launched, you take a photo and then the photo is visualized in a ImageView placed always in the same activity.
Instead of staying there, I'd like to start an intent and visualize the photo in a new activity.
I can't understand where the photo is passed again in the main activity and where/how I should launch a new intent. This is the code:
public class PhotoIntentActivity extends Activity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
private void handleCameraVideo(Intent intent) {
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mVideoView = (VideoView) findViewById(R.id.videoView1);
mImageBitmap = null;
mVideoUri = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
*
* #param context The application's environment.
* #param action The Intent action to check for availability.
*
* #return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
}
Can anyone please help me?
Thanks
The file is saved to the path you get from the your createImageFile() method, which is saved as mCurrentPhotoPath. You can retrieve the photo from this path at any time, as you do in setPic() with BitmapFactory.decodeFile(). Therefore, to view the image in a new Activity, you just have to pass that path to the Intent in onActivityResult():
Intent intent = new Intent(this, ViewActivity.class);
intent.setData(Uri.parse(mCurrentPhotoPath));
startActivity(intent);
Then you can retrieve this path in the new Activity:
String photoPath = getIntent().getData().toString();

Android - Take a picture from the Camera and save it to the internal storage

I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!

Save output image from layout on Android

i want to save output image from layout[redline],
the program, take image picture from camera -> save in sdcard -> load image gray and original to layout. i want to save gray and original image became one image like on the red line.
public class PhotoIntentActivity extends Activity {
private static final String TAG = "Saliency";
private static final int ACTION_TAKE_PHOTO_B = 1;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private ImageView mImageView2;
private Bitmap mImageBitmap;
private View view;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("ImageDataset", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* Decode the JPEG file into a Bitmap */
Mat mInput = new Mat();
mInput = Highgui.imread(mCurrentPhotoPath, CvType.CV_8UC1);
Mat mRgba = new Mat(mInput.rows()/4, mInput.cols()/4, CvType.CV_64FC1);
Imgproc.resize(mInput, mInput, mRgba.size());
Bitmap resultBitmap = Bitmap.createBitmap(mInput.cols(), mInput.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mInput, resultBitmap);
//
Bitmap ImageAsli= BitmapFactory.decodeFile(mCurrentPhotoPath);
Bitmap ImageAsliResize = Bitmap.createScaledBitmap(ImageAsli, ImageAsli.getWidth(), ImageAsli.getHeight(), false);
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(resultBitmap);
mImageView2.setImageBitmap(ImageAsliResize);
mImageView.setVisibility(View.VISIBLE);
mImageView2.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
;
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mImageView2 = (ImageView) findViewById(R.id.imageView2);
mImageBitmap = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(
picBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
//minimal versi froyo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO_B
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this, mLoaderCallback);
}
}
You can get a "screenshot" of any view (including your parent layout) by temporarily enabling the drawing cache on it with setDrawingCacheEnabled() and then calling getDrawingCache() to retrieve a Bitmap of the view. Don't forget to disable the drawing cache after saving the image to improve performance. Save the bitmap to disk using the Bitmap.compress() method.
However please note that the size of your bitmap image will then depend on the size of the device screen. You can get more control by drawing your images directly to a Canvas backed by a mutable Bitmap instead of using a visible layout as source.

Categories

Resources