I basically want to hide the imagesthe user clicks in my app from the user in the gallery, display them in a small imageview and send it to the server. I am doing it the below way. However Bitmap Factory decode gives me a null bitmap I dont know why. Any help would be appreciated.
For creating file to save image to and opening camera intent;
public void openCamera(View view) {
PermissionsClass.checkPermissions(DIalogActivity.this, AppConfig.REQ_WRITE_ACCESS);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(DIalogActivity.this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
//resizeFile(mCurrentPhotoPath);
photoURI = FileProvider.getUriForFile(DIalogActivity.this,
"com.example.sandithaa.nfcreader.fileprovider",
photoFile);
Log.i("photouri", String.valueOf(photoURI));
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(intent, 1);
} else {
Toast.makeText(this, "Camera cannot be opened.", Toast.LENGTH_SHORT).show();
}
}
}
For creating the file:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.i("filepathin createbefore", mCurrentPhotoPath);
return image;
}
For uploading to the server :
private void uploadFile() {
final String path;
Log.i("uplaod pdf", "pdf");
Random r = new Random();
int randomNo = r.nextInt(100000000 + 1);
String name = "IMG" + randomNo;
//getting the actual path of the image
// path = FilePath.getPath(this, photoURI);
// Log.i("path is",path);
Log.i("current parh", mCurrentPhotoPath);
try {
final String uploadId = UUID.randomUUID().toString();
Log.i("in uplaod 1", String.valueOf(priority.getSelectedItem()));
Log.i("proti", incidentEt.getText().toString());
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, "http://technobyteinfo.in/filter-coffee/uploadAll.php")
.addFileToUpload(mCurrentPhotoPath, "pdf") //Adding file
.addParameter("name", name)
.addParameter("description", incidentEt.getText().toString().trim())
.addParameter("priority" +
"", priority.getSelectedItem().toString())
.addParameter("time", time)
.addParameter("longitude", MySharedPreferences.retrievePreferences("longitude", getApplicationContext(), "00.00"))
.addParameter("latitude", MySharedPreferences.retrievePreferences("latitude", getApplicationContext(), "00.00"))
.addParameter("deviceid", GetDeviceId.getMyAndroidDeviceId(getApplicationContext()))
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.setDelegate(new UploadStatusDelegate() {
#Override
public void onProgress(Context context, UploadInfo uploadInfo) {
}
#Override
public void onError(Context context, UploadInfo uploadInfo, Exception exception) {
Toast.makeText(context, "File could not be uploaded.", Toast.LENGTH_SHORT).show();
Log.i("exceptipn", exception.getMessage());
}
#Override
public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
Log.i("error is", serverResponse.getBodyAsString());
JSONObject jObj = null;
try {
jObj = new JSONObject(serverResponse.getBodyAsString());
boolean error = jObj.getBoolean("error");
if (error == false) {
Toast.makeText(context, "Details saved successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "File could not be uploaded.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(Context context, UploadInfo uploadInfo) {
}
})
.startUpload(); //Starting the upload
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Trying to compress the images this way:
public void compressImage() {
try {
OutputStream outStream = null;
Log.i("imagefiename",imageFileName);
outStream = new FileOutputStream(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(imageFileName ,bmOptions);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, outStream);
outStream.flush();
outStream.close();
Log.i("file path compress", mCurrentPhotoPath);
} catch (Exception e) {
Log.i("exception", e.toString());
}
}
My onActivityResult after camera intent comes back:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
compressImage();
Picasso.get().load(photoURI).resize(300,300).into(imageView);
}
Related
I want capture video from camera Intent and save in app directory (don't save video in Device Gallery) and insert video path into database to load and display in my app
i try in my activity :
public class VideoActivity extends Activity {
private TblVideo TBL_VIDEO;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
long date = System.currentTimeMillis();
String string_path = DATABASE_LOCATION + LAST_MOMENT_ID + "_" + date + ".mp4";
File mediaFile = new File(string_path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Button buttonRecording = (Button) findViewById(R.id.photo_btn_take_video);
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
fileUri = Uri.fromFile(mediaFile);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private String SaveMediaFile(int type) {
if (type == MEDIA_TYPE_VIDEO) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mediaFile);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string_path;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
try {
if (resultCode == RESULT_OK) {
insertVideo();
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
but when go to file directory , video size is 0Kb !! and save into device gallery
How to fix this problem ?
thanks
and try this but app is crash :
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
FileOutputStream fileOutputStream = null;
try {
FileInputStream fileInputStream = new FileInputStream(fileUri.getPath());
fileOutputStream = new FileOutputStream(mediaFile);
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
insertVideo();
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
}
}
i use this and save video file after activity result is OK, save video in directory !
private String SaveMediaFile() {
try {
InputStream in = getContentResolver().openInputStream(fileUri); // Uri
OutputStream out = new FileOutputStream(mediaFile); // file
byte[] buf = new byte[1024];
int len;
assert in != null;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو");
}
return string_path;
}
thanks
I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}
In my app I save an image file (a pictures taken from camera phone) but sometimes I get an error if I want to show its thumbnail immediately in an Imageview. Why? Is saving process too slow? Could I use an alternative in order to save my image file?
Here I call my camera:
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.v("Crea file Immagine", "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.v("photofile",String.valueOf(photoFile));
Uri mSelectedImageUri= Uri.fromFile(photoFile);
Log.v("mSelectedImageUri", String.valueOf(mSelectedImageUri));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mSelectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
});
Here I save my image file:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
sharedPreference.save(context,"nomeFile",timeStamp);
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "BottiglieDiVino");
boolean success;
if (!storageDir.exists()) {
success = storageDir.mkdir();
if (success) {
// Do something on success
Log.v("Crea /BottiglieDiVino", "Ho Creato nuova directory");
} else {
// Do something else on failure
Log.v("Crea /BottiglieDiVino", "ERRORE nel creare nuova directory");
}
}
File image = new File(storageDir, timeStamp + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
percorso = image.getAbsolutePath();
sharedPreference.save(context,"percorso", percorso);
Log.v("percorso", percorso);
return image;
}
and here I get this error
java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)
libcore.io.IoBridge.open(IoBridge.java:409)
java.io.FileInputStream.<init>(FileInputStream.java:78)
java.io.FileInputStream.<init>(FileInputStream.java:105)
android.content.ContentResolver.openInputStream(ContentResolver.java:630)
com.example.android.swipetabs.FragmentTab2.decodeSampledBitmapFromUri(FragmentTab2.java:
p.s. in the last line :) is the error.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
percorso = sharedPreference.getValue(context, "percorso");
sharedPreference.save(context,"check23", "ok");
Log.v("percorso", percorso);
foto.setImageBitmap(display(percorso));
}
}
public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
try {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, options);
please help me.
Note:Give these permission run time for marashmallow or above and put your code when permission granted in your other devices it's work fine
In mainfest
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
runtime
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 10;
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
permissions= new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (checkPermissions())
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(demo.this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.v("Crea file Immagine", "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.v("photofile",String.valueOf(photoFile));
Uri mSelectedImageUri= Uri.fromFile(photoFile);
Log.v("mSelectedImageUri", String.valueOf(mSelectedImageUri));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mSelectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
}
});
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(this,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
Everytime the image is captured the folder creation section works fine but the image is not added to the folder
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode != RESULT_CANCELED)
{
folder = new File(Environment.getExternalStorageDirectory() + File.separator+"folder/");
if(!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
}
else
{
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator +"folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath); `
}
}
If I add the folder creation and save image logic to the onclick() directly it shows error stating "Failure delivering result info"
*Please do help *
public void saveBitmapToFile(Bitmap bmp) {
File mAppBaseDir;
if (isExternalStorageWritable())
mAppBaseDir = new File(Environment.getExternalStorageDirectory(), "FolderName");
else
mAppBaseDir = new File(getApplicationContext().getFilesDir().getParent()).getAbsoluteFile();
if (!mAppBaseDir.exists()) {
mAppBaseDir.mkdirs();
}
File imageDir = new File(mAppBaseDir, "Profile");
if (!imageDir.exists())
imageDir.mkdirs();
File file = new File(imageDir + "/" + "profile.png");
if (file.exists()) {
file.delete();
}
try {
writeBytesToFile(file, bitmapToByte(bmp));
} catch (IOException e) {
// show alert for retry choose photo
e.printStackTrace();
}
}
public void writeBytesToFile(File file, byte[] bytes) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
Log.e("", e.getMessage());
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (Exception e) {
Log.e("", e.getMessage());
}
}
}
}
public byte[] bitmapToByte(Bitmap bitmapFinally) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapFinally.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
I answer this question based on your comment "can you please elaborate". CMIIW :
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
folder = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
if (!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
} else {
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
"Ive declared the cameraIntent object before oncreate() method" that's no problem about that, but onActivityResult will be triggered after you call startActivityForResult, then the intent wont have the extra you give
a bit issue in my code, please help me to overcome this
i have an activity which captures an image & saves in app folder which is working fin. on click save button it saves the image in folder but when user cancle camera activity then 0kb file is created as well in folder, how to avoid this
here is my code related to camera activity
public class camera extends Activity {
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 Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private File getAlbumDir() {
String path = Environment.getExternalStorageDirectory().toString();
File filenamedemo = new File(path + "/ImageFolder/");
String name = String.valueOf(filenamedemo);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
if (name != null) {
if (!filenamedemo.mkdirs()) {
if (!filenamedemo.exists()) {
return null;
}
}
}
} else {
}
return filenamedemo;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date(0));
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 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() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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;
}
startActivityForResult(takePictureIntent, ACTION_TAKE_PHOTO_B);
}
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
// setPic();
// galleryAddPic();
mCurrentPhotoPath = null;
Intent viewint = new Intent(camera.this, TashPatti.class);
startActivity(viewint);
finish();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dispatchTakePictureIntent();
/*
* 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) {
if (requestCode == ACTION_TAKE_PHOTO_B) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "picture saved.", Toast.LENGTH_LONG)
.show();
handleBigCameraPhoto();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
Toast.makeText(this, "User cancelled the image capturing.",
Toast.LENGTH_LONG).show();
} else {
// Video capture failed, advise user
Toast.makeText(this, "image capture failed.", Toast.LENGTH_LONG)
.show();
}
}
}
// 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);
}
}
any help will appreciatd,
thank you :)
i solved my issue by deleting the 0 size file, in onActivitiResult(),
i got what i want but it is not clear to me why my code creates 0 size file after cancle operation ??
refrence for others ,enjoy coding
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTION_TAKE_PHOTO_B) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "picture saved.",
Toast.LENGTH_LONG).show();
Bitmap photo = (Bitmap) data.getExtras().get("data");
byte[] byteData = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byteData = baos.toByteArray();
//handleBigCameraPhoto();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
Toast.makeText(this, "User cancelled the image capturing.",
Toast.LENGTH_LONG).show();
} else {
// Video capture failed, advise user
Toast.makeText(this, "image capture failed.",
Toast.LENGTH_LONG).show();
}
//this code delete the file if itz size is 0, 0 size occers wheen user cancles the
//camera activity so to avoid 0 size file in our folder we are deleting it
File file= filePath;
Log.i("lengthhh", Long.toString(file.length()));
if(file.exists() && file.length()==0)
{
file.delete();
}
Intent viewint=new Intent(camera.this, TashPatti.class);
startActivity(viewint); finish();
}
}