How to get actual path of image from Uri in Android Q? - android

I'm taking picture using camera and selecting from gallery. After that doing compression to reduce file size. I was using getRealPathFromURI() method to get actual image path, but in Android QMediaStore.Images.Media.DATA is deprecated.
fun getRealPathFromURI(contentUri: Uri, activityContext: Activity): String {
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor = activityContext.managedQuery(contentUri, proj, null, null, null)
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
As per documentation I tried openFileDescriptor() to gain access:
private fun getBitmapFromUri(context: Context, uri: Uri): Bitmap {
val parcelFileDescriptor = context.contentResolver.openFileDescriptor(uri, "rw")
val fileDescriptor = parcelFileDescriptor?.fileDescriptor
val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
parcelFileDescriptor?.close()
return image
}
also tried this

Due to Scoped Storage, we can’t write the image directly to the desired folder and then update the MediaStore . Instead, Android Q introduces a new field MediaStore.Images.Media.RELATIVE_PATH in which we can specify the path of the image (for example, "Pictures/Screenshots/").
Please refer "Saving a photo to the gallery" section of this blog for more information.

for loading image from gallery you can use it and you have the create provide in manifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"></meta-data>
</provider>
create your #xml/provide_paths like this
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
path="Android/data/package_name/files/Pictures" /> //pictures is the folder where your image will store
</paths>
code:
if (resultCode == Activity.RESULT_OK) { //onActivity you will get the result like this way
if (data != null) {
Uri contentURI = data.getData();
String path = null;
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),contentURI);
path = saveImage(bitmap);
// decodeImage(path);
img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
mCurrentPhotoPath = path;
}
}
public void activeGallery() {// for taking the picture from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE);
}
and for capture image in on Activity use
Bundle bundle=data.getExtras(); //
Bitmap bitmap= (Bitmap) bundle.get("data");
img.setImageBitmap(bitmap);
saveImage(bitmap);
public String saveImage(Bitmap myBitmap) { //this method will compress your image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(JPEG, 90, bytes);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() , ""+IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
// FileOutputStream fos = new FileOutputStream(f);
myBitmap.compress(JPEG, 90, fo);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
public void activeTakePhoto() {// it will go on camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getApplicationContext().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));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}

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" />

Hide camera images from user gallery

Hi I am trying to make the images captured from my app inaccessible to the user. First I tried to save these images to internal storage which didnt work. Then I tried to hide them using "." infront of the folder name.I am not sure what the correct way to do this is. I also tried creating a file called .nomedia to bypass media scanner. I am very confused about the proper way to do this. Here's my code:
public String getImageUri(Context inContext, Bitmap inImage) {
/* *//* ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, ".title", null);
return Uri.parse(path);*//*
*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.myFolder");
file.mkdirs();
File mFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.nomedia");
mFile.mkdirs();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
uri = MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
If I use file.mkdirs() I get filenotfoundexception. If i remove that line I get no errors but my uri is empty.
Does the above function return the file path as well? I need the file path and the uri later on. Any help is appreciated.
I guess you don't have to add another extension or something else just save them in external cache dir of your app and gallery app won't able to read your private directory until unless you notify about them.
so store your camera images here and no gallery app can detect it.
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
sample code
public static File createPictureFile(Context context) throws IOException {
Locale locale = Locale.getDefault();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", locale).format(new Date());
String fileName = "JPEG_" + timeStamp + "_";
// Store in normal camera directory
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(fileName, ".jpg", storageDir);
}
Save your image to internal storage instead. Other applications like MediaScanner or Gallery do not have permission to read from your own application memory. Sample 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();
}
Save the image with different extension.
For example: .jpg can be saved as .ttj.
Try this code. Set where you want to save the photo. Once you receive response on onActivityResult(), in the desired URI, you will get the photo.
public void captureImageFromCamera() {
fileUri = FileUtils.getInstance().getOutputMediaFile(null);
if(fileUri == null){
Utilities.displayToastMessage(ApplicationNekt.getContext(),
context.getString(R.string.unable_to_access_image));
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Following function will give you desired path. Change it based on your project need.
public Uri getOutputMediaFile(String imageNameWithExtension) {
if (imageNameWithExtension == null)
imageNameWithExtension = "image_" + System.currentTimeMillis() + ".jpg";
String extPicDir = getExtDirPicturesPath();
if (!Utilities.isNullOrEmpty(extPicDir)) {
File mediaFile = new File(extPicDir, imageNameWithExtension);
return Uri.fromFile(mediaFile);
} else {
Log.d("tag", "getOutputMediaFile." +
"Empty external path received.");
return null;
}
}
public String getExtDirPicturesPath() {
File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file != null)
return file.getPath();
else
Log.d("", "getExtDirPicturesPath failed. Storage state: "
+ Environment.getExternalStorageState());
return null;
}
To get the resultant photo.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case TAKE_PICTURE:
//fileuri variable has the path to your image.
break;
}

How to take a screenshot of a current Activity and then share it?

I need to take a screenshot of Activity (without the title bar, and the user should NOT see that a screenshot has actually been taken) and then share it via an action menu button "share". I have already tried some solutions, but they didn't work for me. Any ideas?
This is how I captured the screen and shared it.
First, get root view from current activity:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Second, capture the root view:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
Third, store the Bitmap into the SDCard:
public static void store(Bitmap bm, String fileName){
final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
At last, share the screenshot of current Activity:
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I hope you will be inspired by my code.
UPDATE:
Add below permissions into your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Because it creates and accesses files in external storage.
UPDATE:
Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.
Here is a good description how to do it.
create share button with click on listener
share = (Button)findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
});
Add two methods
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Share screen shot. sharing implementation here
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
This Method Doesn't Need to Store and Retrieve Screenshot for Sharing Again.
On just Method Call you will Able to Share Screenshot.
private Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void share(Bitmap bitmap){
String pathofBmp=
MediaStore.Images.Media.insertImage(ctx.getContentResolver(),
bitmap,"title", null);
Uri uri = Uri.parse(pathofBmp);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Star App");
shareIntent.putExtra(Intent.EXTRA_TEXT, "");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity(Intent.createChooser(shareIntent, "hello hello"));
}
Called this Method like this
share(screenShot(view));
By using this Direct Share Screenshot without having READ & WRITE Permission
You can the below code to get the bitmap for the view you are seeing on screen You can specify which view to create bitmap.
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
I couldn't get Silent Knight's answer to work to work until I added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
to my AndroidManifest.xml.
You can take screenshot of any portion of your view.You just need the reference of the layout of which you want the screenshot. for example in your case you want the screen shot of your activity. let assume that your activity root layout is Linear Layout .
// find the reference of the layout which screenshot is required
LinearLayout LL = (LinearLayout) findViewById(R.id.yourlayout);
Bitmap screenshot = getscreenshot(LL);
//use this method to get the bitmap
private Bitmap getscreenshot(View view) {
View v = view;
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
return bitmap;
}
for taking screenshot
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
for saving screenshot
private void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/scrnshot.png"); ////File imagePath
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
and for sharing
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
and simply in the onclick you can call these methods
shareScoreCatch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
});
as of 2021 here is complete answer you would only copy past this code and it should work fine with you, also it uses all the new API including permission launchers, and android q way of saving images
I will be adding one more functionality which is saving inside folder inside Picture folder like this
/Pictures/MyAppName/photos.png
also this code is supporting android < 10 as well as the newer one.
i am making a screen shoot and saving it to desk to get uri of the image, to be able to share it later.
first, permission launcher is required on android < 10
val requestStoragePermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
var saveImageFlag = true
permissions.entries.forEach {
saveImageFlag = it.value
}
if (saveImageFlag) {
shareScreenShootResult()
} else {
showMessage(getString(R.string.cant_share_ScreenShoot))
}
}
val permissionListener: () -> Boolean = {
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
true
} else {
requestStoragePermissionLauncher.launch(
arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
)
false
}
}
then the next method gives the image name and set the directory and then share the image
private fun shareScreenShootResult() {
val dateFormatter by lazy {
SimpleDateFormat(
"yyyy.MM.dd 'at' HH:mm:ss z", Locale.getDefault()
)
}
val filename = "${getString(R.string.my_ScreenShoot)}${dateFormatter.format(Date())}.png"
val ScreenShootFolderPath = File.separator + requireContext().getAppName()
val uri = binding.rootLayout.makeScreenShot()
.saveScreenShot(requireContext(), filename, ScreenShootFolderPath, permissionListener)
?: return
dispatchShareImageIntent(uri)
}
private fun dispatchShareImageIntent(screenShotUri: Uri) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/png"
intent.putExtra(Intent.EXTRA_STREAM, screenShotUri)
startActivity(Intent.createChooser(intent, "Share"))
}
getAppName is an extention funtion, you can add it anywhere in your project then call it on context, do not forget to import it.
fun Context.getAppName(): String {
var appName: String = ""
val applicationInfo = applicationInfo
val stringId = applicationInfo.labelRes
appName = if (stringId == 0) {
applicationInfo.nonLocalizedLabel.toString()
} else {
getString(stringId)
}
return appName
}
this method makeScreenShot is extension function on the View
you better add all extension functions in different file.
fun View.makeScreenShot(): Bitmap {
setBackgroundColor(Color.WHITE)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
draw(canvas)
return bitmap
}
it returns bitmap on which i am calling saveScreenShot which is another extenion function
fun Bitmap.saveScreenShot(
requireContext: Context,
filename: String,
ScreenShootFolderPath: String,
permissionListener: () -> Boolean,
): Uri? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
saveImageInQ(this, filename, ScreenShootFolderPath, requireContext.contentResolver)
else
legacySave(this, filename, ScreenShootFolderPath, permissionListener)
}
private fun saveImageInQ(
bitmap: Bitmap,
filename: String,
parentFileName: String,
contentResolver: ContentResolver
): Uri? {
val fos: OutputStream?
val uri: Uri?
val contentValues = ContentValues()
contentValues.apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.Files.FileColumns.MIME_TYPE, "image/png")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + parentFileName)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
uri =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
uri?.let { contentResolver.openOutputStream(it) }.also { fos = it }
fos?.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
fos?.flush()
fos?.close()
contentValues.clear()
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0)
uri?.let {
contentResolver.update(it, contentValues, null, null)
}
return uri
}
private fun legacySave(
bitmap: Bitmap,
filename: String,
parentFileName: String,
permissionListener: () -> Boolean,
): Uri? {
val fos: OutputStream?
if (!permissionListener()) {
return null
}
val path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() +
parentFileName + File.separator + filename
val imageFile = File(path)
if (imageFile.parentFile?.exists() == false) {
imageFile.parentFile?.mkdir()
}
imageFile.createNewFile()
fos = FileOutputStream(imageFile)
val uri: Uri = Uri.fromFile(imageFile)
fos.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
fos.flush()
fos.close()
return uri
}
For all the Xamarin Users:
Xamarin.Android Code:
Create an external Class (I have an interface for each platform, and I implemented those 3 below functions from android platform):
public static Bitmap TakeScreenShot(View view)
{
View screenView = view.RootView;
screenView.DrawingCacheEnabled = true;
Bitmap bitmap = Bitmap.CreateBitmap(screenView.DrawingCache);
screenView.DrawingCacheEnabled = false;
return bitmap;
}
public static Java.IO.File StoreScreenShot(Bitmap picture)
{
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyFolderName";
var extFileName = Android.OS.Environment.ExternalStorageDirectory +
Java.IO.File.Separator +
Guid.NewGuid() + ".jpeg";
try
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
Java.IO.File file = new Java.IO.File(extFileName);
using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate))
{
try
{
picture.Compress(Bitmap.CompressFormat.Jpeg, 100, fs);
}
finally
{
fs.Flush();
fs.Close();
}
return file;
}
}
catch (UnauthorizedAccessException ex)
{
Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
return null;
}
catch (Exception ex)
{
Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
return null;
}
}
public static void ShareImage(Java.IO.File file, Activity activity, string appToSend, string subject, string message)
{
//Push to Whatsapp to send
Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
Intent i = new Intent(Intent.ActionSendMultiple);
i.SetPackage(appToSend); // so that only Whatsapp reacts and not the chooser
i.AddFlags(ActivityFlags.GrantReadUriPermission);
i.PutExtra(Intent.ExtraSubject, subject);
i.PutExtra(Intent.ExtraText, message);
i.PutExtra(Intent.ExtraStream, uri);
i.SetType("image/*");
try
{
activity.StartActivity(Intent.CreateChooser(i, "Share Screenshot"));
}
catch (ActivityNotFoundException ex)
{
Toast.MakeText(activity.ApplicationContext, "No App Available", ToastLength.Long).Show();
}
}`
Now, from your Activity, you run the above code like this:
RunOnUiThread(() =>
{
//take silent screenshot
View rootView = Window.DecorView.FindViewById(Resource.Id.ActivityLayout);
Bitmap tmpPic = ShareHandler.TakeScreenShot(this.CurrentFocus); //TakeScreenShot(this);
Java.IO.File imageSaved = ShareHandler.StoreScreenShot(tmpPic);
if (imageSaved != null)
{
ShareHandler.ShareImage(imageSaved, this, "com.whatsapp", "", "ScreenShot Taken from: " + "Somewhere");
}
});
Hope it will be of use to anyone.
You can try the below code to capture the screenshot of current screen and share that image without any LIBRARY & PERMISSION. I have tested this its working perfectly.
Just copy paste this.
In MainAtivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button fullPageScreenshot, customPageScreenshot;
private LinearLayout rootContent;
private ImageView imageView;
private TextView hiddenText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());
findViews();
implementClickEvents();
}
/* Find all views Ids */
private void findViews() {
fullPageScreenshot = (Button) findViewById(R.id.full_page_screenshot);
customPageScreenshot = (Button) findViewById(R.id.custom_page_screenshot);
rootContent = (LinearLayout) findViewById(R.id.root_content);
imageView = (ImageView) findViewById(R.id.image_view);
hiddenText = (TextView) findViewById(R.id.hidden_text);
}
/* Implement Click events over Buttons */
private void implementClickEvents() {
fullPageScreenshot.setOnClickListener(this);
customPageScreenshot.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.full_page_screenshot:
takeScreenshot(ScreenshotType.FULL);
break;
case R.id.custom_page_screenshot:
takeScreenshot(ScreenshotType.CUSTOM);
break;
}
}
/* Method which will take screenshot on Basis of Screenshot Type ENUM */
private void takeScreenshot(ScreenshotType screenshotType) {
Bitmap b = null;
switch (screenshotType) {
case FULL:
//If Screenshot type is FULL take full page screenshot i.e our root content.
b = ScreenshotUtils.getScreenShot(rootContent);
break;
case CUSTOM:
//If Screenshot type is CUSTOM
fullPageScreenshot.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of first button
hiddenText.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of hidden text
b = ScreenshotUtils.getScreenShot(rootContent);
//After taking screenshot reset the button and view again
fullPageScreenshot.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of first button again
hiddenText.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of hidden text
//NOTE: You need to use visibility INVISIBLE instead of GONE to remove the view from frame else it wont consider the view in frame and you will not get screenshot as you required.
break;
}
//If bitmap is not null
if (b != null) {
showScreenShotImage(b);//show bitmap over imageview
File saveFile = ScreenshotUtils.getMainDirectoryName(this);//get the path to save screenshot
File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
shareScreenshot(file);//finally share screenshot
} else
//If bitmap is null show toast message
Toast.makeText(this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
}
/* Show screenshot Bitmap */
private void showScreenShotImage(Bitmap b) {
imageView.setImageBitmap(b);
}
/* Share Screenshot */
private void shareScreenshot(File file) {
Uri uri = Uri.fromFile(file);//Convert file path into Uri for sharing
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.sharing_text));
intent.putExtra(Intent.EXTRA_STREAM, uri);//pass uri here
startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
}
}
ScreenshotType.java
public enum ScreenshotType {
FULL, CUSTOM;
}
ScreenshotUtils.java
public class ScreenshotUtils {
/* Method which will return Bitmap after taking screenshot. We have to pass the view which we want to take screenshot. */
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
/* Create Directory where screenshot will save for sharing screenshot */
public static File getMainDirectoryName(Context context) {
//Here we will use getExternalFilesDir and inside that we will make our Demo folder
//benefit of getExternalFilesDir is that whenever the app uninstalls the images will get deleted automatically.
File mainDir = new File(
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Demo");
//If File is not present create directory
if (!mainDir.exists()) {
if (mainDir.mkdir())
Log.e("Create Directory", "Main Directory Created : " + mainDir);
}
return mainDir;
}
/* Store taken screenshot into above created path */
public static File store(Bitmap bm, String fileName, File saveFilePath) {
File dir = new File(saveFilePath.getAbsolutePath());
if (!dir.exists())
dir.mkdirs();
File file = new File(saveFilePath.getAbsolutePath(), fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}
4.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.takescreenshot_demo.MainActivity">
<!-- Button which will take full page screenshot -->
<Button
android:id="#+id/full_page_screenshot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/full_page_screenshot"
android:textColor="#android:color/white"
android:textSize="14sp" />
<!-- Hidden Text which will shown when taking screenshot from below Button -->
<TextView
android:id="#+id/hidden_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/hidden_text"
android:textColor="#android:color/white"
android:textSize="14sp"
android:visibility="invisible" />
<!-- Button which will take screenshot after hiding some view and showing some view -->
<Button
android:id="#+id/custom_page_screenshot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/custom_page_screenshot"
android:textColor="#android:color/white"
android:textSize="14sp" />
<!-- ImageView to show taken Screenshot -->
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
A consolidated copy and paste code:
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
String screenshotPath = mPath;
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
// openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
//Function to share Screenshot
private void shareScreenshots(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
//Function to open screenshot
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
This is how I captured the screen and shared it. Take a look if you are interested.
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}}
see more in : https://www.youtube.com/watch?v=LRCRNvzamwY&feature=youtu.be
If someone is getting an java.io.FileNotFoundException, following SilengKnight's solution, the problem is probably that writing in storage was not permited (Although we added the user-permission in the manifest). I solved it by adding this in the store function before making a new FileOutputStream.
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//Permission was denied
//Request for permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_CODE_EXTERNAL_STORAGE);
}
Create helper class for creating and sharing screen shot
public class share {
private final Context c;
public share(Context c) {
this.c = c;
}
public void shareInt(Bitmap bitmap, String msg, String name) {
Uri uri = getmageToShare(bitmap, name);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_TEXT, msg);
intent.setType("*/*");
c.startActivity(Intent.createChooser(intent, "Share Via").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
// Retrieving the url to share
private Uri getmageToShare(Bitmap bitmap, String name) {
File imagefolder = new File(c.getCacheDir(), "images");
Uri uri = null;
try {
imagefolder.mkdirs();
File file = new File(imagefolder, name+".png");
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 70, outputStream);
outputStream.flush();
outputStream.close();
uri = FileProvider.getUriForFile(c, "com.yourapp.fileprovider", file);
} catch (Exception e) {
Toast.makeText(c, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
return uri;
}
}
Now call this helper class from any activity you want to take screen shot and share
CardView mainView = findViewById(R.id.mainView);
new share(c).shareInt(new getBitmap().screenShot(mainView), "msg", "randomstring");
here mainView is that view which you want to take snap shot, jzt pass view reference.
No need of run time permission coz we are using cache dir
This is what I use to take a screenshot. The solutions described above work fine for API < 24, but for API 24 and greater another solution is needed. I've tested this method on API 15, 24, & 27.
I placed the following methods in MainActivity.java:
public class MainActivity {
...
String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
View sshotView;
...
private boolean checkPermission() {
List arrayList = new ArrayList();
for (String str : this.permissions) {
if (ContextCompat.checkSelfPermission(this, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.isEmpty()) {
return true;
}
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100);
return false;
}
protected void onCreate(Bundle savedInstanceState) {
...
this.sshotView = getWindow().getDecorView().findViewById(R.id.parent);
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_shareScreenshot:
boolean checkPermission = checkPermission();
Bitmap screenShot = getScreenShot(this.sshotView);
if (!checkPermission) {
return true;
}
shareScreenshot(store(screenShot));
return true;
case R.id.option2:
...
return true;
}
return false;
}
private void shareScreenshot(File file) {
Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.STREAM", fromFile);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show();
}
}
public static Bitmap getScreenShot(View view) {
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
return createBitmap;
public File store(Bitmap bitmap) {
String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots";
File file = new File(str);
if (!file.exists()) {
file.mkdirs();
}
file = new File(str + "/sshot.png");
try {
OutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show();
}
return file;
}
}
I placed the following permissions and provider in my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redtiger.applehands">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
...
<provider
android:name="com.redtiger.applehands.util.GenericFileProvider"
android:authorities="${applicationId}.com.redtiger.applehands.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
...
</application>
</manifest>
I created a file called provider_paths.xml (please see below) to direct the FileProvider where to save the screenshot. The file contains a simple tag that points to the root of the external directory.
The File was placed in the resource folder res/xml (if you don't have an xml folder here, just create one and place your file there).
provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>

Android: Saving an image to directory

I'm trying to save a bitmap to my directory but haven't a little trouble.
What my applications does is:
1.Opens the inbuilt camera application by an Intent.
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
2.It then stores the picture intent into 'REQUEST_IMAGE_CAPTURE' and saves the image into a temp directory.
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
3.Which is then converted into a bitmap and loaded from the tmp directory into an image view
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
Now, how do i save the bitmap which in the imageview into the picture directory?
I have inputted the permissions into my manifest
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
use bitmap.compress in order to direct the bitmap into an OutputStream.
for example:
FileOutputStream fo = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap
private void saveImage(Bitmap bmp, String filePath){
File file = new File(filePath);
FileOutputStream fo = null;
try {
boolean result = file.createNewFile(); // true if created, false if exists or failed
fo = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY_PERCENT, fo);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fo != null) {
try {
fo.flush();
fo.close();
} catch (Exception ignored) {
}
}
}
}
Note that filePath is directory + filename e.g. /sdcard/iamges/1.jpg

How to save image in android gallery

I try to save the image into WathsappIMG but when I go to image gallery android I don't see the image and the image there into the directory can be seen from ES File Explorer
OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/WhatSappIMG/");
dir.mkdirs();
// Retrieve the image from the res folder
BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable();
Bitmap bitmap1 = drawable.getBitmap();
// Create a name for the saved image
File file = new File(dir, "Wallpaper.jpg" );
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the gallery don't displaying (necessarily) files from external storage.
this is a common mistake.
the gallery displays images stored on the media store provider
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
here is what you should enter, when you're about to save the picture in the Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
That code will add the image at the end of the Gallery. so please, check your Gallery picture, to be sure
Try adding this:
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Fill in your details for yourBitmap, yourTitle, and yourDescription, or just leave it as "".
You need to add a MediaScannerConnection class to your function of saving the image to the gallery. This class scans for new files and folders in gallery connected with your app. Add the following class to scan the newly saved image files or new added image directory to the gallery or download Source Code
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Read more
For Xamarin fellows:
public static void SaveToTheGalley(this string filePath, Context context)
{
var values = new ContentValues();
values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
values.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/jpeg");
values.Put(MediaStore.MediaColumns.Data, filePath);
context.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
}
And don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission.
As
MediaStore.MediaColumns.Data
and
MediaStore.Images.Media.insertImage
is deprecated now,
here is how I did it using bitmap
fun addImageToGallery(
fileName: String,
context: Context,
bitmap: Bitmap
) {
val values = ContentValues()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
}
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
context.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
}
}
}
You should change this piece of code-
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
String url = Images.Media.insertImage(getContentResolver(), bitmap1,
"Wallpaper.jpg", null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly refer this code worked for me:
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
// First save the picture
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
//Compress and save pictures by io stream
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
//Insert files into the system Gallery
//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//Update the database by sending broadcast notifications after saving pictures
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
Use the following code to make your image visible in the gallery.
public void saveImageToGallery(Context context, Uri path) {
// Create image from the Uri for storing it in the preferred location
Bitmap bmp = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bmp = MediaStore.Images.Media.getBitmap(contentResolver, path);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, path);
bmp = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
// Store image to internal storage/ImagePicker directory
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ImagePicker";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
// Broadcast the image & make it visible in the gallery
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
Toast.makeText(context, "File saved to gallery", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Failed to save", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources