I'm using this code to save images in the SD card (simulated or real) but all the testers of my app are telling me that the have a new folder in their Photos app with all my images (I don't know why on my Nexus 4 with KK this is not happening).
static public void storeImage(Bitmap image, String imgName) {
String root = Environment.getExternalStorageDirectory().toString();
File myRoot = new File(root + "/files");
if (!myRoot.exists()) {
myRoot.mkdir();
}
File myDir = new File(root + "/images/");
if (!myDir.exists()) {
myDir.mkdir();
}
File file = new File(BasePathToFile(imgName));
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to change de visibility, security or something to avoid that the Photos App or any App get access to my folder??
After reading a lot I have found this in the android dev page.
So at the end if you want that your files remain private you have to store them in the device.
So I have change my code to this:
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(context.getFilesDir(), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I hope this will be useful to someone.
Happy coding.
A #Sebastian pointed getExternalFilesDir(String type) is a more complete solution so i have changed de code to this:
private static Boolean SdMemoryExist() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
static public String BasePath(Context context) {
String _basePathToCheck;
if (SdMemoryExist()) {
_basePathToCheck = context.getExternalFilesDir(null).toString() + File.separator;
} else {
_basePathToCheck = context.getFilesDir().toString() + File.separator;
}
return _basePathToCheck;
}
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(BasePath(context), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding.
Related
How can change image saving location i have created the folder but how to save image in it. all downloaded images are saved in pictures folder
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file = new File(Environment.getExternalStorageDirectory().getPath() + "/CreativeGraphy");
if (!file.exists()) {
file.mkdir();
}
try {
file.createNewFile();
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}
Use this method
public static void saveBitmap(String path, Bitmap bitmap) {
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
After saving you can call scanFile method to index your file in the gallery.
MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
thanks everyone This works
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CreativeGraphy";
File dir = new File(file_path);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir,name );
FileOutputStream fOut;
try {
MediaStore.Images.Media.insertImage(r, bitmap, name, desc);
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
Toast.makeText(context, "Download succeed ", Toast.LENGTH_SHORT).show();
}
I get my Image and video in Uri. I want to save that file in specific folder in internal memory. I tried Fileoutputstream and all but I can save it in camera folder but not specific folder. I want to save both image and video.
public void onClick(View view) {
if (string.contains("jpg")) {
String path = null;
try {
path = MediaStore.Images.Media.insertImage(getContentResolver(),
string, "img", null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Uri uri = Uri.parse(path);
Toast.makeText(getApplicationContext(), "Image saved", Toast.LENGTH_LONG).show();
saveImageandVideo(uri);
} else {
Uri uri = Uri.parse(string);
saveImage(uri);
Toast.makeText(getApplicationContext(), "Video saved", Toast.LENGTH_LONG).show();
}
}
});
my save code here
private void saveImageandVideo(Uri uri) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/folder_name");
if (!myDir.exists()) {
myDir.mkdirs();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
This code work but I can't able to save it in specific folder. It automatically saved it in camera folder(DCIM). and I can't able to save the videos. waiting for answers friends. Thanks in advance :D
Change your file variable creation as follows.
String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
File myDir = new File(root + "/folder_name");
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File(myDir,"filename.jpg/mp4");
//rest of your code
Change your saveImageandVideo() as
private void saveImageandVideo() {
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Im trying to save a bitmap as a file however its failing for some reason
Thats the error I keep getting, it only pops up on 5.0 however I tested it on 6.0 sdk and its working fine
java.io.FileNotFoundException: /storage/sdcard/Pictures/mFile/image1491238127.jpg: open failed: EISDIR (Is a directory)
private File saveBitmap(Bitmap bitmap, String path) {
File file = null;
if (bitmap != null) {
file = new File(path);
file.mkdirs();
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
}
private File saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-Fashom" +".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();
}
return file;
}
As I observe on your code I found you creating file.mkdir(); it means you creating a new file not get u need to write the code after try catch return exception.
try {
//it gets file path
file = new File(path);
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
ting the exist file..
So I implement picasso, so I can download images and save them on sd cart, so when I want i can use them on the program.
I have a for loop:
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).into(target);
}
But I just get into target once and its the last one of for loop,
target code:
private Target target = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
//new Thread(new Runnable() {
//#Override
//public void run() {
/*
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),caminho);
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, caminho);
if (!myDir.exists()) {
myDir.getParentFile().mkdirs();
//myDir.createNewFile();
}
FileOutputStream out = null;
out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//}
//}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
};
I commented the thread because it does the same thing with or without, if you want you cant uncomment.
I have alredy search about it, but i couldnt find any answer for this problem, all the URL are ok!
I have been been doing this for 3 days, and it keep the same.
YES listaProdutos.size() = 4;
AND all the url are ok!
If u didnt understand the question, please say.
Why not use the following code? No Targets are used here, so no target is getting gc'ed
I took the freedom to optimize your code a little as well. I've done this without testing the code, but it should work without any problems.
new Thread(new Runnable(){
#Override
public void run(){
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, caminho);
if (!myDir.exists()) {
if(myDir.getParentFile().mkdirs()){
//myDir.createNewFile();
FileOutputStream out = null;
out = new FileOutputStream(myDir);
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).get().compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
}catch{IOException e) {
e.printStackTrace();
}
}
}
}).start();
You can create a class implementingTarget:
class MyTarget implements Target {
String name;
public MyTarget(String name) {
this.name = name;
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
//new Thread(new Runnable() {
//#Override
//public void run() {
/*
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),caminho);
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
try {
verifyStoragePermissions(AtividadePrincipal.this);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/imagensDaApp");
myDir = new File(myDir, name);
if (!myDir.exists()) {
myDir.getParentFile().mkdirs();
//myDir.createNewFile();
}
FileOutputStream out = null;
out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//}
//}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
};
And use it inside the cycle:
for (int i = 0; i < listaProdutos.size(); i++) {
caminho =listaProdutos.get(i).getImagem();
Picasso.with(getApplicationContext()).load("URL"+listaProdutos.get(i).getImagem()).into(new MyTarget(caminho ));
}
I am receiving a stream from the server. That stream represents a PDF, and I KNOW it is a pdf file. I am receiving it, and storing in the phone this way:
ResponseBody body=response.body();
File dir = new File(Environment.getExternalStorageDirectory() + “/myApp/“+variable+"/“+anotherVariable);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, objetoFichero.get("nombre").getAsString());
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
InputStream is = body.byteStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
fos.flush();
fos.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This way, the file is created, but using a file browser I try to open the pdf, and it opens, but it is blank.
Any idea about what I am doing wrong?
Thank you.
Assuming you have the document (the pdf) as a byteArray (documentBytes)
I would:
createUri(this, new File(getCacheDir(), "pdf/whateverNameYouWant.pdf"), documentBytes)
public static Uri createUri(#NonNull final Context context, final File name, #NonNull final byte[] data) throws IOException {
final File parent = name.getParentFile();
if (!parent.exists()) {
FileUtils.mkdirs(parent, null);
}
final OutputStream out = new FileOutputStream(name);
try {
out.write(data);
} finally {
StreamUtils.closeSilently(out);
}
return createUri(context, name);
}
public static void mkdirs(final File dir) {
if (!dir.mkdirs()) {
Log.w("File", "Failed to mkdirs: " + dir);
}
}
public static void closeSilently(#Nullable final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (final Throwable ignore) {
}
}
}
You can then show the document with the uri received by createUri()