Save Image from drawable to sdcard in camera activity - android

I'm working on a project, that read image file from drawable folder through ImageView, it loaded successfully through
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setOnTouchListener(this);
buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
now after pressing takePicture button , image should save in sdcard, it is taking snapshot but not saving the image with that, the code is below
File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Toast.makeText(AndroidCamera.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
Please help me for this issue....Thanks in advance

You can save photos in Android without the need for an OutputStream and all the other logic that accompanies it. Here is a simple recipe which will do what I think you are trying to accomplish. Pay special attention to the Intent and how it is used to set up the saving of the image, as this is I think where you are going wrong.
public class PhotoActivity extends Activity implements OnClickListener {
private Button takePicture;
private String path;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
takePicture = (Button) findViewById(R.id.button1);
takePicture.setOnClickListener(this);
path = Environment.getExternalStorageDirectory() + "/my_image.png";
imageFile = new File(path);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivity(i);
break;
}
}
}

private static final int CAMERA_REQUEST = 1888;
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
photo = (Bitmap) data.getExtras().get("data");
}
}
private Uri getImageUri() {
File file1 = new File(Environment.getExternalStorageDirectory() + "/Camerafolder");
if (!file1.exists())
{
file1.mkdirs();
}
File file = new File(Environment.getExternalStorageDirectory() + "/Camerafolder/"+"img"+".png");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}

Related

How to take and save picturte and get picture path via button?

Here, I want To take picture and save it on sd card and get path via button.
That the picture path can see into TextView.
how can i do it?
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
Button camera;
Button path;
TextView tvPath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImage = (ImageView) findViewById(R.id.camera_image);
path = (Button) findViewById(R.id.btnPath);
tvPath = (TextView) findViewById(R.id.tvPath);
//1
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(thumbnail);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sorry for English.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
Uri filePath = data.getData();
String fullFilePath = FilePath.getPath(this, filePath);
if (fullFilePath != null) {
String filename = fullFilePath.substring(fullFilePath.lastIndexOf("/") + 1);
tvFilename.setText(filename);
}
}

How to not save image captured with camera in an self made folder?

Hello everyone! I am using a camera which saves photo's in the phones gallery. But I don't want to save the photo in the gallery. I want to save it somewhere else. So all i need is not to save it automatically in the gallery.
This is my code:
public class MainActivity extends AppCompatActivity {
ImageView photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.btnPhoto);
photo = (ImageView) findViewById(R.id.imgPhoto);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
photo.setImageBitmap(bitmap);
}
}
If my question is not good enough, please ask me! And please help me out.
This method for open camera and path is File declare global.
private void openCamera() {
Logger.i("openCamera");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
File rootPath = new File(Environment.getExternalStorageDirectory(), "folderName");
if (!rootPath.exists())
rootPath.mkdirs();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String snapshotImage = df.format(new Date()) + ".jpg";
rootPath = new File(rootPath + "/" + snapshotImage);
path = rootPath;
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
get result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
// Float Latitude=0.0f, Longitude=0.0f;
imageDvr.setImageURI(Uri.parse(path.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
}
and also give per\mission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You will get the bitmap of image in onActivityResult(), and you will store that Image by bitmap.
Use below function to store image on your self made folder. you need to make that folder and need to use path of that.
like this.
public void SaveImage(Bitmap showedImgae){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/YourSelfMadeFolder");
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);
}
You can add intent android.provider.MediaStore.EXTRA_OUTPUT with your URI:
private File getOutputMediaFile() {
File mediaStorageDir = null;
String state = Environment.getExternalStorageState();
if (state.contains(Environment.MEDIA_MOUNTED)) {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
} else {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
}
if (!mediaStorageDir.exists()) {
Logger.d("Desc", "File dir " + mediaStorageDir.mkdirs());
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"Image_" + timeStamp + ".jpg");
return mediaFile;
}
your button click:
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri mImageCaptureUri = null;
File mediaFile = getOutputMediaFile();
mImageCaptureUri = Uri.fromFile(mediaFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
this.startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
}}0;
on activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FilePath","Path"+mediaFile.getAbsolutePath();)
}

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private 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 selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.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"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
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();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});

Android transfer the system camera and then display the pictures in the ImageView

I know that call system camera is
Intent intent = new Intent();
intent.setAction("android.media.action.STILL_IMAGE_CAMERA");
startActivity(intent);
i want display the pictures in the ImageView,but i don't konw how to do it.
is there anybody can give me a sample code?
edit1:
i also need store
String strPath = Environment.getExternalStorageDirectory().toString();
File path = new File(strPath);
if(!path.exists())
path.mkdirs();
strFileName = "test.jpg";
strFilePath = strPath + "/" + strFileName;
File file = new File(strFilePath);
Uri uri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
i use the up code to store, but how to see in photographic time?that is preview.
You need to use startActivityForResult instead of startActivity, and then grab the result in onActivityResult. Something like this:
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent 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_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}

Saving/renaming taken photos on sd-card in Android

i've used code from link below,was very helpfull,thank you:
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html
need help with some photo issues! takePhoto() starts MediaStore.ACTION_IMAGE_CAPTURE, getFile() creates "Image keeper" directory and then saves taken picture under "Image-SOMENUMBER.jpg" name!in onActivityResult() i'd like to show taken picture as ImageView and i'd like to rename picture to something user inputs in edittext or something!
have two questions:
1) why can't i get ImageView to show my picture in try{} part? what am i doing wrong? how can i get a path of saved image?
2) is there a way i can enable users to name photos the way they want?(something like "save as" or renaming on some button click ect.)
any idea is welcome!thank you!
here is the code:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), "Image keeper" );
if(!path.exists()){
path.mkdir();
}
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
File file = new File(path,name);
return file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
final File file = getFile(this);
try {
Bitmap captureBmp;
captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(captureBmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
couldn't solve renaming part of my problem but this piece of code did a job for me! i'm sure it can be done a bit fancier but it works! it involves taking picture, saving to sd card and getting path to it!
ImageView iv;
static File image;
Uri ImageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
}
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
image = getFile(this);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), "Image keeper" );
if(!path.exists()){
path.mkdir();
}
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
File fileimage = new File(path, name);
return fileimage;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
try {
Bitmap captureBmp;
captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(image) );
ImageUri = Uri.fromFile(image);
String pathToImage = ImageUri.getPath();
iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(captureBmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.setAdjustViewBounds(true);
break;
}
}
}

Categories

Resources