What i want to do: delete an image file from the private internal storage in my app. I save images in internal storage so they are deleted on app uninstall.
I have successfully created and saved:
String imageName = System.currentTimeMillis() + ".jpeg";
FileOutputStream fos = openFileOutput(imageName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 35, fos);
an image that i receive through
bitmap = BitmapFactory.decodeStream(inputStream);
I am able to retrieve the image later for display:
FileInputStream fis = openFileInput(imageName);
ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
DataOutputStream outWriter = new DataOutputStream(bufStream);
int ch;
while((ch = fis.read()) != -1)
outWriter.write(ch);
outWriter.close();
byte[] data = bufStream.toByteArray();
bufStream.close();
fis.close();
imageBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
I now want to delete this file permanently. I have tried creating a new file and deleting it, but the file is not found:
File file = new File(imageName);
file.delete();
I have read on the android developer website that i must open private internal files using the openFileInput(...) method which returns an InputStream allowing me to read the contents, which i don't really care about - i just want to delete it.
can anyone point me in the right direction for deleting a file which is stored in internal storage?
Erg, I found the answer myself. Simple answer too :(
All you have to do is call the deleteFile(imageName) method.
if(activity.deleteFile(imageName))
Log.i(TAG, "Image deleted.");
Done!
Related
I tried following code to get the user's google profile pic, but this is giving only thumbnail size blur photo:
FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
This is giving me uri, which when converted to string shows following URL (URL is showing pic, but due to privacy modified few digits here):
https://lh3.googleusercontent.com/a-/AguE7mDKNdcXubEW0cMTTYzschAykXcWRQDYeMlHb8rf_g=s96-c
I am able to use this url to show picture in an ImageView using Picasso, but not sure how to download it & store in phone memory.
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString()).fit().into(profileImage);
I tried following by converting getPhotoURL into bitmap:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(SplashActivity.this.getContentResolver(), userPhotoURLUri);
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
But this is giving me exception at the very first line:
FileNotFoundException: No content provider: for google getphotouri
Following code worked for me.
As the google profile pic doesn't contains .jpg or .png in its url therefore all other methods are not working.
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(YourActivity.this);
//Set the Image dimension here it will not reduce the image pixels
googleProfilePic = acct.getPhotoUrl().toString().replace("s96-c", "s492-c");
Glide.with(MainActivity.this).load(googleProfilePic).asBitmap().into(new BitmapImageViewTarget(imageView) {
#Override
protected void setResource(Bitmap resource) {
FileOutputStream outStream = null;
File dir = new File(myfolderPath);
String fileName = picName + ".jpg";
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.flush();
resource.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
}
Try this:
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl()).fit().into(profileImage);
BitmapDrawable draw = (BitmapDrawable) profileImage.getDrawable();
Bitmap bitmap = draw.getBitmap();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try{
FileOutputStream outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
}catch (Exception e) {
e.printStackTrace();
}
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can use Android's Download Manager to have it handle the download:
// Create the Download Request
DownloadManager.Request downloadRequest = new DownloadManager.Request(myPhotoUri);
// Set the destination
// (You can include the "SubPath/FileName" as the second argument if you want the file in a sub directory)
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, myFileName);
// Display a notification while the download is in progress and after it's completed
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Allow the media scanner to find the file
downloadRequest.allowScanningByMediaScanner();
// Enqueue the download
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(downloadRequest);
Additionally, if you want your app to perform an operation in response to the completed download, you would register a BroadcastReceiver filtering DownloadManager.ACTION_DOWNLOAD_COMPLETE Intents and check for the Download id returned by .enqueue().
Here's further information on DownloadManager and DownloadManager.Request you can use to customize your download options:
https://developer.android.com/reference/android/app/DownloadManager
https://developer.android.com/reference/android/app/DownloadManager.Request
I'm new to android and developing an app that saves large images from drawable folder to phone storage. These files have resolution of 2560x2560 and I want to save these files without loosing image quality.
I use following method to save images and it gives me Out of Memory Exception. I have seen many answers how to load a large bitmap efficiently. But I cant really find an answer for this problem.
In my code, I use
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId);
File file = new File(root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg");
file.createNewFile();
FileOutputStream oStream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, oStream);
oStream.close();
bitmap.recycle();
Is there anything wrong with my code? This works without any exception for smaller images.
If I use android:largeHeap="true", this does not throw any exception. But I know it is not a good practice to use android:largeHeap="true".
Is there any efficient way to save large images from drawable folder without an exception?
Thank you in advance.
If you just want to copy the image file, you shouldn't decode it into a bitmap in the first place.
You can copy a raw resource file with this for example:
InputStream in = getResources().openRawResource(imageId);
String path = root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg";
FileOutputStream out = new FileOutputStream(path);
try {
byte[] b = new byte[4096];
int len = 0;
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
}
}
finally {
in.close();
out.close();
}
Note that you have to store your image in the res/raw/ directory instead of res/drawable/.
i want to save a svg file from web to a file and then show it from file. i use this code to save a png file :
OutputStream fos = null;
File file = new File(getApplicationContext().getCacheDir(),FilenameUtils.getBaseName(url.toString())+FilenameUtils.getExtension(url.toString()));
Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.PNG, 50, bos);
bos.flush();
bos.close();
what should i do for svg file ?
In theory, you should be able to do something like the following:
PictureDrawable pd = (PictureDrawable) imageView.getPicture();
Picture picture = pd.getPicture();
picture.writeToStream(os);
However you should not do this. writeToStream() is deprecated (as is createFromStream()). I presume the reason is that the format of a Picture may change in the future and any saved pictures may no longer load. If you are just using it for temporary caching while the app is running, then that may be okay.
But it would be better, as #greenapps says, to cache the original SVGs.
I'm writing a process that downloads/ copies a file attached to Gmail on to the SD card that my application can then read.
When a user clicks on the attachment my activity is fired and I use the following code to save to local storage;
InputStream in = getContentResolver().openInputStream( intent.getData() );
String ext = intent.getType().equals("text/xml") ? ".xml" : ".gpkg";
localFile = new File( TILE_DIRECTORY, "tmp/"+intent.getDataString().hashCode()+ext);
// If we haven't already cached the file, go get it..
if (!localFile.exists()) {
localFile.getParentFile().mkdirs();
FileIO.streamCopy(in, new BufferedOutputStream(new FileOutputStream(localFile)) );
}
The FileIO.streamCopy is simply;
public static void streamCopy(InputStream in, OutputStream out) throws IOException{
byte[] b = new byte[BUFFER];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
out.close();
in.close();
}
This all works fine on a small file, but with a 6Mb attachment only 12Kb is ever getting written. I'm not even getting an error, the process just runs through very quickly and i'm left with a corrupt file.
This process is run in its own thread and is part of a larger app with a lot of fileIO, so there is no issue with permissions/ directories etc.
Is there something different I should be doing with the stream?
Incidentally, intent.getData() is
content://gmail-ls/mexxx#gmail.com/messages/6847/attachments/0.1/BEST/false
and intent.getType() is
application/octet-stream
Thanks
All work's fine with this code
InputStream in = new BufferedInputStream(
getContentResolver().openInputStream(intent.getData()) );
File dir = getExternalCacheDir();
File file = new File(dir, Utils.md5(uri.getPath()));
OutputStream out = new BufferedOutputStream( new FileOutputStream(file) );
streamCopy(in, out);
I'm trying to share an image in an app I have made that downloads an Image and writes it to a file. But any time I try to share it, it says can't upload file or just does nothing. It's not coming up in the logcat so I'm kinda stuck for ideas on how to fix it.
The image that is downloaded is displayed in an image view like this
iView.setImageBitmap(im);
String path = ContentFromURL.Storage + "/temp.jpg";
File temp = new File(path);
uri = Uri.fromFile(temp);
iView.setImageURI(uri);
Asynch task to download file
HttpURLConnection connection;
try {
String url = params[0];
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset","UTF-8");
connection.connect();
InputStream input = connection.getInputStream();
image = BitmapFactory.decodeStream(input);
File temp = new File(Storage,"temp.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = new FileOutputStream(temp);
fo.write(bytes.toByteArray());
fo.close();
String path = temp.getAbsolutePath();
Log.d("Asynch", "image shuould exist");
SharePage.act.runOnUiThread(new Runnable()
{
public void run()
{
SharePage.setImage(image);
}
}
);
creating intent
twitterIntent = new Intent(Intent.ACTION_SEND);
twitterIntent.setClassName("com.twitter.android",packageName);
twitterIntent.setType("image/jpeg");
twitterIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(twitterIntent);
I know that I should use the built in android share thing but its not working either when I try to share the image
The problem was where I was trying to store the Image, I wanted to have it so that the user never saw the image and it was deleted when it wasn't needed anymore but the other apps didn't have access to the directory. So I have since moved it to the external storage directory.