Android - Save images in an specific folder - android

I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.
MainActivity.java
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Folder is already created
String dirName = Environment.getExternalStorageDirectory().getPath()
+ "/MyAppFolder/MyApp" + n + ".png";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
n++;
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Go through the following code , its working fine for me.
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

I have used mdDroid's code like this:
public void startCamera() {
// Create photo
newPhoto = new Photo();
newPhoto.setName(App.getPhotoName());
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}
}

Use Like this. It will work for you.
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
filename= f.getName();
Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
cursor.close();
//Convert file path into bitmap image using below line.
// yourSelectedImage = BitmapFactory.decodeFile(filePath);
Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
//put bitmapimage in your imageview
//yourimgView.setImageBitmap(yourSelectedImage);
Savefile(filename,filePath);
}
}
}
public void Savefile(String name, String path) {
File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
if(!direct.exists()) {
direct.mkdir();
}
if (!file.exists()) {
try {
file.createNewFile();
FileChannel src = new FileInputStream(path).getChannel();
FileChannel dst = new FileOutputStream(file).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help you. for reference to use camera intent.

Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .
public void addToFav(String dirName, Bitmap bitmap) {
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
dirName + System.currentTimeMillis() + ".jpg";
Log.e("resultpath",resultPath);
new File(resultPath).getParentFile().mkdir();
if (Build.VERSION.SDK_INT < 29){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
if(fileOutputStream != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}else {
OutputStream fos = null;
File file = new File(resultPath);
final String relativeLocation = Environment.DIRECTORY_PICTURES;
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
final ContentResolver resolver = getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, contentValues);
try {
fos = resolver.openOutputStream(uri);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fos != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
}
}

I have found an easier code to do it.
This is the code for creating the image folder:
private File createImageFile(){
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/App Folder/";
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AppName_" + timeStamp;
String file = dir +imageFileName+ ".jpg" ;
File imageFile = new File(file);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
,And this is the code for launching the camera app and take the photo:
public void lunchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ziad.sayit",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Useful link for different ways of doing it: https://www.programcreek.com/java-api-examples/?class=android.os.Environment&method=getExternalStoragePublicDirectory

Related

Save image from camera without being resized

I use the following code to create image file and save them in to sd card
private File createImageFile(Bitmap bitmap) throws IOException {
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
PICNAME,
".png",
storageDir);
FileOutputStream out = null;
try {
out = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
The issue is that, though I take picture in full screen mode but the above code always saves the image in very less amount of dimension which is 320x240. why so.. is there by any means that I can save the image without resizing?
you can do it like this :
public static Uri takePhotoByCamera(Activity activity) {
File publicDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/myFolder");
double d = new Random().nextDouble();
File file = new File(publicDirectory, d + ".jpg");
String path = file.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
values.put(MediaStore.MediaColumns.TITLE, "New Picture");
values.put(MediaStore.Images.ImageColumns.DESCRIPTION, "From your Camera");
activity.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Uri photoUri = Uri.parse("file://" + path);
if (!publicDirectory.exists())
publicDirectory.mkdirs();
else if (!publicDirectory.isDirectory() && publicDirectory.canWrite()) {
publicDirectory.delete();
publicDirectory.mkdirs();
} else {
Log.d("tag550", "can't access");
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
activity.startActivityForResult(intent, requestCamera);
return photoUri;
}

Android Studio save image into new directory [duplicate]

I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.
MainActivity.java
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Folder is already created
String dirName = Environment.getExternalStorageDirectory().getPath()
+ "/MyAppFolder/MyApp" + n + ".png";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
n++;
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Go through the following code , its working fine for me.
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have used mdDroid's code like this:
public void startCamera() {
// Create photo
newPhoto = new Photo();
newPhoto.setName(App.getPhotoName());
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
Use Like this. It will work for you.
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
filename= f.getName();
Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
cursor.close();
//Convert file path into bitmap image using below line.
// yourSelectedImage = BitmapFactory.decodeFile(filePath);
Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
//put bitmapimage in your imageview
//yourimgView.setImageBitmap(yourSelectedImage);
Savefile(filename,filePath);
}
}
}
public void Savefile(String name, String path) {
File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
if(!direct.exists()) {
direct.mkdir();
}
if (!file.exists()) {
try {
file.createNewFile();
FileChannel src = new FileInputStream(path).getChannel();
FileChannel dst = new FileOutputStream(file).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help you. for reference to use camera intent.
Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .
public void addToFav(String dirName, Bitmap bitmap) {
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
dirName + System.currentTimeMillis() + ".jpg";
Log.e("resultpath",resultPath);
new File(resultPath).getParentFile().mkdir();
if (Build.VERSION.SDK_INT < 29){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
if(fileOutputStream != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}else {
OutputStream fos = null;
File file = new File(resultPath);
final String relativeLocation = Environment.DIRECTORY_PICTURES;
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
final ContentResolver resolver = getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, contentValues);
try {
fos = resolver.openOutputStream(uri);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fos != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
}
}
I have found an easier code to do it.
This is the code for creating the image folder:
private File createImageFile(){
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/App Folder/";
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AppName_" + timeStamp;
String file = dir +imageFileName+ ".jpg" ;
File imageFile = new File(file);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
,And this is the code for launching the camera app and take the photo:
public void lunchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ziad.sayit",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Useful link for different ways of doing it: https://www.programcreek.com/java-api-examples/?class=android.os.Environment&method=getExternalStoragePublicDirectory

how to get the file path and name in android?

I crated one image store in sd card to save that image and then i need that image path and name of the image pls tell how to get the name and path of the image
public void saveBitmap(Bitmap bmp)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/NewFolder";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "myImage.png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
String name = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/NewFolder";
storedimagepath=name.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
i got this
void getImageCAMERandGALLERY()
{
final String [] items = new String[] { "Take from Camera" , "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.select_dialog_item , items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter , new DialogInterface.OnClickListener() {
private Uri mImageCaptureUri;
#Override
public void onClick(DialogInterface dialog , int item)
{
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(android.provider.MediaStore.EXTRA_OUTPUT , mImageCaptureUri);
try
{
intent.putExtra("return-data" , true);
startActivityForResult(intent , PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
} else
{
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();
dialog.show();
}
#Override
protected void onActivityResult(int requestCode , int resultCode , Intent data)
{
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null)
{
Bitmap photo = extras.getParcelable("data");
UserImage.setImageBitmap(photo);
try
{
Uri tempUri = getImageUri(getApplicationContext() , photo);
storeUriInFile(tempUri);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public Uri getImageUri(Context inContext , Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG , 100 , bytes);
String path = Images.Media.insertImage(inContext.getContentResolver() , inImage , "Title" , null);
return Uri.parse(path);
}
void storeUriInFile(Uri uri)
{
try
{
Bitmap my_btmp = Media.getBitmap(this.getContentResolver() , uri); // BitmapFactory.decodeStream(BufferedInputStream);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
my_btmp.compress(CompressFormat.PNG , 0 , bos);
byte [] bitmapdata = bos.toByteArray();
long timeinmilliseconds = new Date().getTime();
// store byte array in a image file
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath , SpeakerBox_FOLDER);
if (!file.exists())
file.mkdirs();
String mFileName = file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";
OutputStream out = new FileOutputStream(mFileName);
out.write(bitmapdata);
out.flush();
out.close();
String filename = mFileName;
storedimagepath = filename;
} catch (Exception e)
{
}
}
you can try like that
String name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/NewFolder";
storedimagepath=name.toString();
File f = new File(storedimagepath+"/photo.jpg");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
ImageView mImgView1 = (ImageView)findViewById(R.id.imageView);
mImgView1.setImageBitmap(bmp);

Captured image is not stored in the specific folder in android

I have created a program to capture the image and that is getting stored into sdcard/dcim/camera folder. Now I am trying to save the captured image in my own directory created in sdCard, say "/somedir".
I am able to make the directory programmatically but the image file is not getting stored in it.
Can anybody tell me where I am doing wrong here??
Here is the code....
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
Bitmap mybitmap1; //mybitmap1 contain image. So plz dont consider that I don't have image in mybitmap1;
if(!folder.exists())
{
success = folder.mkdir();
Log.i("Log", "folder created");
}
else
{
Log.i("Log", "Folder already present here!!");
}
String fname = date +".jpg";
file = new File( folder,fname);
if (file.exists ())
file.delete ();
capturedImageUri = Uri.fromFile(file);
FileOutputStream out;
byte[] byteArray = stream.toByteArray();
try {
out = new FileOutputStream(file);
mybitmap1.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), mybitmap1, file.getName(), file.getName());
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
Refer the below code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == 1 ) {
final Uri selectedImage = data.getData();
try {
bitmap = Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ filename);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are settings the wrong file name for the file. Just use this method if you want to use time in the name of image file.
private Uri getImageUri() {
// Store image in dcim
String currentDateTimeString = getDateTime();
currentDateTimeString = removeChar(currentDateTimeString, '-');
currentDateTimeString = removeChar(currentDateTimeString, '_');
currentDateTimeString = removeChar(currentDateTimeString, ':');
currentDateTimeString = currentDateTimeString.trim();
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM", currentDateTimeString + ".jpg");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}
private final static String getDateTime() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
return df.format(new Date());
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
return r.toString();
}
Hers is what you need to do:
instead of
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
do this
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/abc");
if(folder.exists()){
//save your file then
}
else{
folder.mkdirs();
//save your file then
}
Make sure you use the neccessary permissions in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

The captured image from camera is not storing in full size

I know this question has been asked so many times in this forum. But still I couldn't get the solution.
Basically in my application, I am calling an inbuilt camera intent, capturing image and displaying a bitmap in imageview and storing it in sd card. Now the image what i get in my folder is of small size like a thumbnail.
My code is
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(cameraIntent, "Select picture"), CAMERA_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null) {
imageView.setImageBitmap(photo);
}
// Image name
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[] { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATE_TAKEN };
Cursor c1 = cr.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null,
null, p1[1] + " DESC");
if (c1.moveToFirst()) {
String uristringpic = "content://media/external/images/media/" + c1.getInt(0);
Uri newuri = Uri.parse(uristringpic);
String snapName = getRealPathFromURI(newuri);
Uri u = Uri.parse(snapName);
File f = new File("" + u);
String fileName = f.getName();
editTextPhoto.setText(fileName);
checkSelectedItem = true;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
// Storing Image in new folder
StoreByteImage(mContext, bitmapdata, 100, fileName);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
// Delete the image from the Gallery
getContentResolver().delete(newuri, null, null);
}
c1.close();
}
} catch (NullPointerException e) {
System.out.println("Error in creating Image." + e);
} catch (Exception e) {
System.out.println("Error in creating Image." + e);
}
System.out.println("*** End of onActivityResult() ***");
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public boolean StoreByteImage(Context pContext, byte[] pImageData,
int pQuality, String pExpName) {
String nameFile = pExpName;
// File mediaFile = null;
File sdImageMainDirectory = new File(
Environment.getExternalStorageDirectory() + "/pix/images");
FileOutputStream fileOutputStream = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap myImage = BitmapFactory.decodeByteArray(pImageData, 0,
pImageData.length, options);
if (!sdImageMainDirectory.exists()) {
sdImageMainDirectory.mkdirs();
}
sdImageMainDirectory = new File(sdImageMainDirectory, nameFile);
sdImageMainDirectory.createNewFile();
fileOutputStream = new FileOutputStream(
sdImageMainDirectory.toString());
BufferedOutputStream bos = new BufferedOutputStream(
fileOutputStream);
myImage.compress(CompressFormat.JPEG, pQuality, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Toast.makeText(pContext, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(pContext, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
and ImageView in main.xml is
<ImageView
android:id="#+id/test_image"
android:src="#drawable/gray_pic"
android:layout_width="180dp"
android:layout_height="140dp"
android:layout_below="#id/edit2"
android:layout_toRightOf="#id/edit3"
android:layout_alignParentRight="true"
android:layout_marginTop="7dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
/>
With this code i get an Imageview and the image stores in my folder with small size.
If I add intent.putExtra then neither image captured displays in ImageView nor image creates in new folder.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
path += "/myFolder/myPicture.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
cameraIntent.putExtra("output", outputFileUri);
startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), CAMERA_REQUEST);
}
Don't know where I am struck..
Any help on this would be appreciated.
Use Camera intent as:
Intent photoPickerIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Select Picture"),TAKE_PICTURE);
//getTempFile()
private Uri getTempFile() {
// if (isSDCARDMounted()) {
File root = new File(Environment.getExternalStorageDirectory(), "My Equip");
if (!root.exists()) {
root.mkdirs();
}
Log.d("filename",filename);
File file = new File(root,filename+".jpeg" );
muri = Uri.fromFile(file);
photopath=muri.getPath();
Item1.photopaths=muri.getPath();
Log.e("getpath",muri.getPath());
return muri;
// } else {
// return null;
}
//}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
else
return false;
}
And Check in your Folder, click on thumbnail it will show actual image

Categories

Resources