I'm trying to obtain the filepath of my stored Image that's stored like so after using the ACTION_IMAGE_CAPTURE intent:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageOne.setImageBitmap(imageBitmap);
SaveImageOne(imageBitmap);
}
SaveImageFunction
private void SaveImageOne(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-1.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This way I can store this 'filepath' of the stored File to SharedPreferences to be accessed later on and say passed into the ACTION_SEND as an image attachment.
after this line out.close(); write this line
String pathString = file.getAbsolutePath(); // gives you the path of the file
now use it how you want it
Related
Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.
I have a png file in a folder "Movies" on the sdcard. I want to copy and rename that file in the same folder. I'm confused on how to properly call the method SaveImage.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
isbn = scanningResult.getContents();
SaveImage();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private void SaveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Movies/");
String fname = "Image-"+ isbn +".jpg";
File file = new File (myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I simply want to duplicate the same file and rename it
Thanks for making it more clearly. You can use this to copy from source file to destination file.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
So your question is, how to properly call your SaveImage(Bitmap finalBitmap) method, right ? as your SaveImage method get a Bitmap as parameter you need to send it a Bitmap as parameter.
You can use BitmapFactory to create a Bitmap object from your file and send this Bitmap object to your SaveImage method :
String root = Environment.getExternalStorageDirectory().toString();
Bitmap bMap = BitmapFactory.decodeFile(root + "/Movies/myimage.png");
SaveImage(bMap);
Rename file:
File source =new File("abc.png");
File destination =new File("abcdef.png");
source.renameTo(destination);
Copy File:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path source=Paths.get("abc.png");
Path destination=Paths.get("abcdef.png");
Files.copy(source, destination);
I got an error in console crashes & anrs. This error is showing sometimes and I couldn't find where the problem is.
java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
The function code to save picture is:
public static String sharePhoto(Context context, Bitmap bmp) {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Folder");
boolean success = true;
String file_path = null;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
file_path = folder + "/Img_" + System.currentTimeMillis() / 1000 + ".jpg";
}
OutputStream os = null;
try {
os = new FileOutputStream(file_path);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Do something else on failure
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file_path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
return file_path;
}
Try this:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/MyFolder");
Thing is that getExternalStorageDirectory() returns File. You need to get absolute path of that file and concatenate with "/Pictures/MyFolder".
i'm trying to capture image with android native camera, the save image is good but doesnt contain the usual EXIF data (gps tags, orientation...)
what do i need to do to save also the EXIF?
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(android.provider.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 = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
imageuri = Uri.fromFile(photoFile);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
}
}
/*Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);*/
}
}
#SuppressLint("SimpleDateFormat")
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Following is the method to Save an Image with EXIF Data (Location Data) to Gallery:
private String saveToGallery (Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to Directory
String photoDir = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM + "/";
File directory = new File(photoDir);
// Creates image file with the name "newimage.jpg"
File myfilepath = new File(directory, "newimage.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myfilepath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitgallery.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.flush();
fos.close();
myfilepath.setReadable(true, false);
} catch (Exception e) {
e.printStackTrace();
}
Uri bitmapUri = Uri.fromFile(myfilepath);
String currentImageFile = bitmapUri.getPath();
//Writes Exif Information to the Image
try {
ExifInterfaceEx exif = new ExifInterfaceEx(currentImageFile);
Log.w("Location", String.valueOf(targetLocation));
exif.setLocation(targetLocation);
exif.saveAttributes();
} catch (Exception e) {
e.printStackTrace();
}
// Updating Gallery with the Image (Sending Broadcast to Gallery)
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentImageFile);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
return directory.getAbsolutePath();
}
The new image is not parsed, as it should be, by the MediaScanner. This smells like a device-specific bug.
See Image, saved to sdcard, doesn't appear in Android's Gallery app for workarounds.
Here is the function to save the Image,
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>