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"/>
Related
enter image description here
please someone help me "To save an image file with increment at end of file name" like("image 1.jpg , image 2.jpg , etc..")
here is my code
please some help me to make this,i am new learner to android-studio.
private File saveBitMap(Context context, View drawView) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()+"/"+"Frames");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated) {
Log.i("ATG", "Can't create directory to save the image");
}
return null;
}
String filename = pictureFileDir.getPath() +File.separator+"Frame"+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery( context,pictureFile.getAbsolutePath());
return pictureFile;
}
If I have understood your question properly then, I assume you want your pictureFile name to be appended by an integer (in auto-incrementing fashion).
You could do that by maintaining a global variable as int imageCount = 1
and then appending it while creating fileName
int imageCount = 1;
private File saveBitMap(Context context, View drawView) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()+"/"+"Frames");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated) {
Log.i("ATG", "Can't create directory to save the image");
}
return null;
}
String filename = pictureFileDir.getPath() +File.separator+"Frame"+ System.currentTimeMillis()+""+(imageCount++)+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery( context,pictureFile.getAbsolutePath());
return pictureFile;
}
I have one android application which have share image function as well save image. This functions are working fine in other than android 6.0 . When I try to share image with whatsapp as well other application, image does not getting attached. My java code for share image like below. What Should I correct for solve the issue ?
Thanks Friends for support :)
protected String doInBackground(String... args) {
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Hindi Picture/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share Image"));
pDialog.dismiss();
}
});
}
I've been working out how to take a screenshot programmatically in android, however when it screenshots I get a toolbar and black screen captured instead of what is actually on the screen.
I've also tried to screenshot a particular TextView within the custom InfoWindow layout I created for the google map. But that creates a null pointer exception on the second line below.
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
Is there anyway to either actually screenshot what is on the screen without installing android screenshot library or to screenshot a TextView within a custom InfoWindow layout
This is my screenshot method:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I have changed the method to the one provided from the source
How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?
However it does not screenshot anything.
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
Use this code
private void takeScreenshot() {
AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
objUsefullData.showProgress("Please wait", "");
}
#Override
protected Void doInBackground(Void... params) {
try {
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmapscreen_shot = Bitmap.createBitmap(v1
.getDrawingCache());
v1.setDrawingCacheEnabled(false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
} else {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Create a media file name
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
imageFile = new File(folder.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
/*
* Toast.makeText(AddTextActivity.this,
* "saved Image path" + "" + imageFile,
* Toast.LENGTH_SHORT) .show();
*/
imageFile.createNewFile();
} else {
/*
* Toast.makeText(AddTextActivity.this,
* "Image Not saved", Toast.LENGTH_SHORT).show();
*/
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
bitmapscreen_shot.compress(CompressFormat.JPEG, 100,
ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Log.e("image_screen_shot", "" + imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
objUsefullData.dismissProgress();
}
};
asyc.execute();
}
Hope this will help you
I have figured it out !
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
Bitmap b = bitmap;
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
String filepath = timeStamp + ".jpg";
try{
OutputStream fout = null;
fout = openFileOutput(filepath,MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
saveImage(filepath);
}
};
mMap.snapshot(callback);
}
/**
* Method to save the screenshot image
* #param filePath the file path
*/
public void saveImage(String filePath)
{
File file = this.getFileStreamPath(filePath);
if(!filePath.equals(""))
{
final ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show();
}
else
{
System.out.println("ERROR");
}
}
I have adapted the code from this link so it doesn't share and instead just saves the image.
Capture screen shot of GoogleMap Android API V2
Thanks for everyones help
Please try with the code below:
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
Bitmap bitmap = null;
Bitmap bitmap1 = null;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
try {
if (bitmap != null)
bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
v1.getWidth(), v1.getHeight());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I faced this issue. After v1.setDrawingCacheEnabled(true); I added,
v1.buildDrawingCache();
And put some delay to call the takeScreenshot(); method.
It is fixed.
My app downloads a PDF file from webserver and opens it with Adobe Reader. But when I click back button on Adobe Reader, my app restarts. I don't want my app to restart when closing Adobe Reader. Note: My app has a file browser dialog, I choose a PDF and display it.
How can I prevent restarting the acitivity when turn back from Adobe Reader?
My code ...
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/dokuman.pdf
String fileName = strings[1]; // -> dokuman.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "dokuman");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
Downloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
...
public class Downloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...
new DownloadFile().execute(host+"dene.pdf", "dokuman.pdf");
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/dokuman/" + "dokuman.pdf"); // -> filename = dokuman.pdf
Uri path = Uri.fromFile(pdfFile);
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(MainActivity.this, "No PDF Viewer App!", Toast.LENGTH_SHORT).show();
...
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;
}