i want too save images in my own directory this is perhaps the directory on which the images are been saved
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
and this is were i am giving my image uri Target where the image will going to be save
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
how can i achive that by making my own directory and saving image there
Hi I would liked to share the method to create and Save the Images in Your Custom Directory as follows :
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(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();
}
}
You should supply the Bitmap Object to be saved and the Directory Name in which You want to Save as follows :
createDirectoryAndSaveFile(imageToSave,fileName);
I have tried to take a picture and then crop it then stored it on SDCard. Here are codes, maybe you will be inspired:
Take a photo:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(AVATAR_FILE_TMP));
intent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CODE_TAKE_PHOTO);
Then crop the photo:
if (requestCode == CODE_TAKE_PHOTO) {
cropImage(Uri.fromFile(AVATAR_FILE_TMP));
}
public void cropImage(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 400);
intent.putExtra("outputY", 400);
intent.putExtra("return-data", true);
startActivityForResult(intent, CODE_CROP_IMAGE);
}
And at last, store the picture:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
// civAvatar.setImageBitmap(photo); // 把图片显示在ImageView控件上
FileOutputStream fos = null;
try {
// store the picture
fos = new FileOutputStream(AVATAR_FILE);
photo.compress(Bitmap.CompressFormat.PNG, 100, fos);// (0-100)compress file.
AVATAR_FILE_TMP.deleteOnExit();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
IoUtils.closeSilently(fos);
finish();
}
}
And if you just store the picture, intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(AVATAR_FILE_TMP)); is OK.
The solution involving heavy Bitmaps is (IMHO) irrelevant when your phone or camera is taking JPEGs.
See the solution here for an almost instantaneous solution: https://stackoverflow.com/a/7982964/5426777
new FileOutputStream(myPath).write(byte[] myPictureCallbackBytes)
Related
After i updated the code to include Fileprovider for API 24 and above, i am getting the error "Gallery keeps stopping".
Below is the code segment for capturing image from camera and performing crop and saving it.
When i traced the code, it execute till startActivityForResult(cropIntent,3) in performcrop() then gives the above error. (Note: there is not much info in error dump, Tested on Nexus 7.0).
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 2)
{
Bundle extras = data.getExtras();
Bitmap var_Bitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
var_Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
try {
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"master"+File.separator);
createDir.mkdir();
File file = new File(root + "master" + File.separator +"master.jpg");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
path1=root + "master" + File.separator +"master.jpg";
//imageUri= Uri.fromFile(file);
if (Build.VERSION.SDK_INT > 23)
imageUri = FileProvider.getUriForFile(RecognizeActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
file);
else
imageUri= Uri.fromFile(file);
} catch (IOException e) {
// e.printStackTrace();
}
performCrop();
} else if (requestCode==3)
{
Bundle extras = data.getExtras();
Bitmap var_Bitmap = (Bitmap) extras.get("data");
ImageView imageView1 = (ImageView) findViewById(R.id.ui_imageView_browse);
imageView1.setImageBitmap(var_Bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
var_Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
try {
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"master"+File.separator);
createDir.mkdir();
File file = new File(root + "master" + File.separator +"master.jpg");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
path1=root + "master" + File.separator +"master.jpg";
} catch (IOException e) {
// e.printStackTrace();
}
ImageView imageView_error = (ImageView) findViewById(R.id.ui_imageView_error);
imageView_error.setVisibility(View.VISIBLE);
imageView_error.setImageResource(R.drawable.process);
userupdate();
if(netcheck==0)
{
FeedTask ft = new FeedTask();
ft.execute(path1);
}
}
}
public void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(imageUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "false");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
// indicate output X and Y
cropIntent.putExtra("outputX", 300);
cropIntent.putExtra("outputY", 300);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent,3);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
As a work around , targetSdkVersion is set to 23 in manifest file and removed the Fileprovider path code segment and it is working fine.
Getting image Content from Gallery picture
Now, I want to copy this image file(Which is picked from gallery) to my Internal App folder PICTURE directory(/storage/emulated/0/Android/data/MYApppackage/files/Pictures/).
I am creating new File in PICTURE Directory. file is created in internal AppDir / data / Pictures Directory and image with .JPG format but not showing image. Image is not visible. Image file is created with 0KB data.
I think its a file writing related issue or other i dont know.
Intent intent ;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
MainActivity.state = "AddBalance";
startActivityForResult(intent, REQUEST_GALLERY);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY);
}
OnActivity Result of Gallery PickUp
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GALLERY:
if (data != null) {
if (data != null) {
Bitmap bitmap=null;
uri1 = data.getData();
// showPhotoDialog(uri1);
try {
// bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri1);
InputStream image_stream = getActivity().getContentResolver().openInputStream(uri1);
bitmap= BitmapFactory.decodeStream(image_stream);
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG,"Data URI----"+data.getData());
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "PNG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".PNG", // suffix
storageDir // directory
);
// File imageFile= new File(storageDir,imageFileName);
FileOutputStream out;
try {
// out = getActivity().openFileOutput(image.getName(), Context.MODE_PRIVATE);
out = new FileOutputStream(image.getName());
/* ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);*/
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception e) {e.printStackTrace();}
// copyFile(new File(getRealPathFromURI(uri1)), image);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
}
Edit : Infos
getting value of uri1 from pickup gallery image : content://com.android.providers.media.documents/document/image%3A25877
I am Trying to write bitmap to File. Here is my Code. getBitmap from REQUEST_GALLERY and URI works fine . I am making File in Enviroment.PICTURE directory and write via OutPutStream. but Still File : PNG_54342323111.PNG
I also tried with ByteArrayOutputStream which you can see in comments but didnt works. also tried with OpenFileOutput but not working.
I'm a total newbie in Android programming and I'm having trouble figuring how to save an image to a specific folder. Let's say i have a folder called "myCapturedImages" and I would to save it in this folder/directory. The directory is located at Internal Storage\Pictures\myCapturedImages. The pictures that I took has its size of 0 bytes and cannot be opened. I think the main problem is my onPictureTaken function. Any clue on how I should achieve the expected save directory?
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(VuzixCamera.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
get the Bitmap of the image and For saving Image you can use this code
//showedImgae is your Bitmap image
public void SaveImage(Bitmap showedImgae){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/DCIM/myCapturedImages");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
showedImgae.compress(Bitmap.CompressFormat.JPEG, 100, out);
Toast.makeText(activityname.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
}
this is simple program to launch camera and save picture to specific folder...
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
Make sure that you have added WRITE_EXTERNAL STORAGE and CAMERA permissions in manifest file.
in my app I take a picture and save it in specified way. My phone is Nexus 4 and the camera is very strong and every picture is about 2.31MB how can I save picture for example in 60KB?
Can I do it with code? and how?
File newdir = new File(dir);
if(!newdir.exists()){
newdir.mkdirs();
}
picturesCount++;
String file = dir+picturesCount+".jpg";
imagePath = file;
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
When you are using camera and picture is taken, you can perform the task in the method below to reduce the quality of the image and type like JPEG or PNG (PNG takes more space than JPEG) so just play with the value (60 current out of 100) and see the difference in size.
#Override
public void onPictureTaken(byte[] data, Camera camera) {
InputStream in = new ByteArrayInputStream(data);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap preview_bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
preview_bitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
byte[] byteArray = stream.toByteArray();
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(new File(
Environment.getExternalStorageDirectory(), "Image1.jpg"));
outStream.write(byteArray);
outStream.close();
} catch (FileNotFoundException e) {
Log.d("CAMERA", e.getMessage());
} catch (IOException e) {
Log.d("CAMERA", e.getMessage());
}
}
I can take a picture via the following intent
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then in the onActivityResult method I set the image taken to an ImageView and attempt to store the image to the SD card with the following function
private void savePic(Bitmap bmp) {
if(!isSDOK || !isSDWritable)
return;
String name = "TESTA";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path,name+".jpg");
path.mkdirs();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bitmapdata);
try{
InputStream is = bis;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read();
os.write(data);
is.close();
os.close();
}catch(Exception e){Log.e("IMAGE CONVERT ERR", e.toString());}
return;
}
When I check the PICTURES folder i see the file but the image is blank and always 12kb in size. Can't I use my above method to save the image from a bitmap file?
Yes as per the CommonsWare comment you can use EXTRA_OUTPUT like this:
private void capturePhoto() {
File root = new File(Environment.getExternalStorageDirectory(), "Folder");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "filename.jpeg");
Uri outputFileUri = Uri.fromFile(file);
Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, TAKE_PICTURE);
}