In my app, i can take a picture and save in gallery(folder 'camera').But i need save it in a specific folder in external memory.This is my code.How i can do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_pic);
init();
getPic.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);
if (resultCode == RESULT_OK) {
Bundle ex = data.getExtras();
bitmap = (Bitmap) ex.get("data");
myPic.setImageBitmap(bitmap);
}
}
This should do it:
private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
How to Save Image in Internal Storage and show image in imageView in another acitivity ,please tell me how to save that image in internal storage because many phones have only internal storage not sd card
this is my first acitivity
//camera
camera = (ImageView) findViewById(R.id.takePic);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName=getPictureName();
File imageFile=new File(pictureDirectory,pictureName);
pictureUri=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
}
});
private String getPictureName() {
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp=sdf.format(new Date());
return "Plane place image"+timestamp+".jpg";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==RESULT_OK){
if (resultCode==CAMERA_REQUEST_CODE)
{
pictureUri = data.getData();
if (pictureUri!=null) {
Intent intent = new Intent(this, PictureActivity.class);
intent.setData(pictureUri);
intent.putExtra("imgUrl", pictureUri.toString());
startActivity(intent);
}
}
}
}
this is my second activity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("ashish", bundle.getString("imgUrl") + "");
path = Uri.parse(bundle.getString("imgUrl"));
}
ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);
i am store image in emulator internal storage used below code...
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
make changes in opencamera method like used below code...
private void OpenCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap thumbnail = null;
if (resultCode==RESULT_OK){
if (requestCode==CAMERA_REQUEST_CODE)
{
thumbnail = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(this, DbInsert.class);
intent.putExtra("name", thumbnail);
startActivity(intent);
}
}
}
second Activity...
Bitmap bitmap = getIntent().getExtras().getParcelable("name");
imageView.setImageBitmap(bitmap);
The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
this is my code it store captured picture form camera and save it on the SDcard but Now i want to enhance this code to taking pictures every 5 seconds If any body having an idea how to do this ,please share
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pictureCounter = 10;
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should implement a runnable interface that uses threads. This way you could call the function on the OnClick method, then call Thread.sleep(timeinmilliseconds), then call the function inside the onClick method again, as many times as needed.
Here is an example of how to use threads:
http://www.wideskills.com/java-tutorial/java-threads-tutorial
I need to write text file in the smartphone internal memory, and then need to copy this .txt file to your computer via the USB cable and accessing his memory (This copy process will make manual, need to locate this file and understand which memory location will be recorded).
I am using the code below, which shows no errors when I run, but I do not know if this recording, and I do not know exactly what directory on your smartphone it should be.
This function is the button to call the function salvarInternalStorage
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Trilateration tri = new Trilateration(v.getContext());
try {
tri.salvarInternalStorage("Trying to Save This text Example");
} catch (IOException e) {
e.printStackTrace();
}
startListBeaconsActivity(DistanceBeaconActivity.class.getName());
}
});
This function is where you should write to the "File.txt" the text passed by parameter.
public void salvarInternalStorage(String texto) throws IOException{
// Use Activity method to create a file in the writeable directory
FileOutputStream fos = context.openFileOutput("FileTeste.txt", context.MODE_PRIVATE);
// Create buffered writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(String.valueOf(texto.getBytes()));
writer.close();
}
With SAF:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createFile("text/plain","Arquivo.txt");
}
private static final int WRITE_REQUEST_CODE = 43;
private void createFile(String mimeType, String fileName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
// Filter to only show results that can be "opened", such as
// a file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested MIME type.
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==WRITE_REQUEST_CODE&&resultCode==RESULT_OK)
alterDocument(data.getData());
}
private void alterDocument(Uri uri) {
try {
ParcelFileDescriptor txt = getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(txt.getFileDescriptor());
fileOutputStream.write(("Tentando Gravar Esse Texto Exemplo").getBytes());
fileOutputStream.close();
txt.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or you can use the OPEN_DOCUMENT_TREE once to choose a directory and after that you have all permissions to save any file under that directory without ask the user. Something like this:
Uri sdCardUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 1:
if (resultCode == Activity.RESULT_OK) {
sdCardUri = data.getData();
getContentResolver().takePersistableUriPermission(sdCardUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
createFile();
break;
}
}
private void createFile() {
DocumentFile sdCard=DocumentFile.fromTreeUri(this,sdCardUri);
DocumentFile createFile=sdCard.findFile("teste.txt");
if (createFile==null)
createFile=sdCard.createFile("text","teste.txt");
OutputStream outStream = null;
try {
outStream = getContentResolver().openOutputStream(createFile.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
String teste="Isto é um teste";
outStream.write(teste.getBytes());
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks
String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}
first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}