Get last captured image? - android

I have an application, where you can take a picture about yourself (the app saves the image in a specified folder called "MyAppImage"), and I want to display the taken image in a second activity with a code, how to do this? I want to display it in a imageView in my SecondActivity, but I need a code that can get the last captured camera image from this folder, is there any way to do this?
Hope someone can guide me, how to do this, thanks!

After take photo:
MainActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = "yourPhotoName" + ".jpg"
filePath = "pathOfMyAppImageFolder" + fileName;
File destination = new File(filePath);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
intent.putExtra("filePath", filePath)
startActivity(intent);
}
});
AnotherActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
filePath = intent.getStringExtra("filePath");
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
Take the last photo of the folder:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<File> files = getListFiles(new File("MyAppImageFolderPath"));
File imgFile = files.get(files.size());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".jpg")){ //change to your image extension
inFiles.add(file);
}
}
}
return inFiles;
}

Once you takePhoto, save it into file.
Then call intent to start second activity and putExtraString with your image file path.
That is all.

Related

How to create folder in internal storage and save captured image

I want to capture image and save it to specific folder in internal storage. Currently i am able to open intent and get thumbnail of captured image. I dont want to user extrnal stotage as now mostly users use their internal storage and not sd card.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
LayoutInflater inflater = LayoutInflater.from(LeaveApplicationCreate.this);
final View view = inflater.inflate(R.layout.item_image,attachView, false);
ImageView img = view.findViewById(R.id.img);
AppCompatImageView btnRemove = view.findViewById(R.id.btnRemove);
img.setImageBitmap(imageBitmap);
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachView.removeView(view);
}
});
attachView.addView(view);
File directory = new File(Environment.getExternalStorageDirectory(),"/Digimkey/Camera/");
if (!directory.exists()) {
directory.mkdir();
}
File file = new File(directory, System.currentTimeMillis()+".jpg");
try (FileOutputStream out =new FileOutputStream(file)) {
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
First gain Write Permissions.
File directory = new File(Environment.getExternalStorageDirectory(), dirName);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, fileName);
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream out =new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
There are two types of storage.
1) Internal ex. "/root/.."
Unless you have rooted device, we can't access. this path.
2) External ex. "/storage/emuated/0"
Environment.getExternalStorageDirectory()
By using this path, we are able to create a directory/file.
Use to method to save your bimap in local storage. Pass bimap image as parameter i.e saveToInternalStorage(imageBitmap)
private String saveToInternalStorage(Bitmap bitmapImage){
//set image saved path
File storageDir = new File(Environment.getExternalStorageDirectory()
+ "MyApp"+ "/Files");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File mypath=new File(storageDir,"bitmap_image.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Required permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

set SD card image to ImageView?

I have an images in SD card i want to take image from SD card and set in the ImageView.please help me guys i have tried the below code.
My Code:
sendImageFromFolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri=null;
ArrayList<Uri> arrayList=new ArrayList<Uri>();
ImageView imageView= (ImageView) findViewById(R.id.imageView);
File pictues= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String[] listOfPictures=pictues.list();
for(String s:listOfPictures){
uri=Uri.parse("file://"+ pictues.toString() +"/"+s);
arrayList.add(uri);
}
InputStream inputStream = null;
FileOutputStream fileOutputStream=null;
Bitmap bmp;
try {
inputStream = getContentResolver().openInputStream(arrayList.get(0));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
bmp = BitmapFactory.decodeStream(bufferedInputStream);
imageView.setImageBitmap(bmp);
}
File pictureFile = new File("Path to your image");
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
mImage.setImage(bitmap);

Image is does not show in ImageView dynamically from sdcard

In My Code The image is not open in ImageView from sdcard i already checked the permissions in 'manifest.xml'.
Same if i try to open it using static name then it will showed by ImageView but not dynamically.
Main Activity
private OnClickListener OnCapture = new OnClickListener() {
#Override
public void onClick(View v) {
String time = mCamUtils.clickPicture();
nextActivity = new Intent(MainActivity.this,EffectActivity.class);
nextActivity.putExtra("ImageName", time);
startActivity(nextActivity);
finish();
}
};
EffectActivity
public class EffectActivity extends Activity {
Intent getActivity = null;
ImageView image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.effectactivity);
getActivity = getIntent();
String name = getActivity.getStringExtra("ImageName");
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
Toast.makeText(getApplicationContext(), path, Toast.LENGTH_LONG).show();
image = (ImageView) findViewById(R.id.imageView1);
File f = new File(path);
byte[] b = new byte[(int)f.length()];
if(f.exists())
{
try
{
if(f.exists())
{
FileInputStream ff = new FileInputStream(f);
ff.read(b);
Bitmap g = BitmapFactory.decodeFile(path);
image.setImageBitmap(g);
ff.close();
}
else
{
Toast.makeText(getApplicationContext(), "ELSE", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
}
}
}
}
I am trying to open image which i saved in before this activity and i catch the name of image here but that does not show the image.
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
In this line try changing "JPG" into "jpg".i think your file extension might be in lowercase letter and it might say f.exists false.
Hope it will help.
String fname = "Pic-" + System.currentTimeMillis() + ".png";
File image= new File(imagesFolder, fname);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
try this code

save camera image into directory

I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly

problem with my feel for HTC android application

I want to create an application that takes a picture and redisplays the application.
But my feeling with my htc code does not work when I tested it on a samsung and it works.
My code:
public class CameraDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button cameraButton = (Button) findViewById(R.id.button1);
cameraButton.setOnClickListener( new View.OnClickListener(){
public void onClick(View v ){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK){
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
}
}
Can you help me understand why it does not work on my htc sensation while it works on another phone.
THANKS.
I came across this problem when working with HTC camera too.
From what I recall HTC / Sense handles the return photo slightly differently, here's some pseudo of how I did it to hopefully handle the two variants of handling photos..
public static void StartCameraActivity()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
// Create the directory if it's not there
File photoDir = new File(Environment.getExternalStorageDirectory() + "/.pics/");
photoDir.mkdirs();
// Construct the file..
String fileName = File.separator + ".pics/photo" + String.valueOf(System.currentTimeMillis()) + ".jpg";
File file = new File(Environment.getExternalStorageDirectory(), fileName);
// Create the intent and remember the place we asked for the file to be placed
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, LinearLayout.VERTICAL );
_outputFileUri = Uri.fromFile(file);
context.getActivity().startActivityForResult(intent, 1);
}
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = SAMPLE_SIZE;
try
{
bm= (Bitmap) data.getExtras().get("data");
FileOutputStream out = new FileOutputStream(_outputFileUri.getPath());
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
catch (NullPointerException ex)
{
bm = OtherImageProcessing(options);
}
catch (Exception e)
{
throw new Exception("Problem occured.", e);
}
public static Bitmap OtherImageProcessing(BitmapFactory.Options options) throws Exception
{
Bitmap bm = null;
try
{
FileInputStream fis = new FileInputStream(_outputFileUri.getPath());
BufferedInputStream bis = new BufferedInputStream(fis);
bm = BitmapFactory.decodeStream(bis, null, options);
// cleaning up
fis.close();
bis.close();
}
catch (Exception e)
{
throw new Exception("Problem", e);
}
return bm;
}
Hope that helps...

Categories

Resources