how can i change bitmap saving location - android

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();
}

Related

Failing to store bitmap as a file

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..

Just go to the target once and it should go 4 times. Picasso/Target

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 ));
}

All my images are public to all android installed apps

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.

android-how to save a view to sd card

i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}

Save button not working

i have bitmap image when return result and then i want to save it in Photo Art Camera folder in SD card but it is not saved. it shows the toast "Photo Not Saved Sucessfully".
This is the code:
mSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
File cacheDir;
Bitmap bitmap = result;
// String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Date d = new Date();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "Photo Art Camera");
} else { cacheDir = MainActivity.this.getCacheDir(); }
if (!cacheDir.exists()) { cacheDir.mkdirs(); }
File file = new File(cacheDir, "PhotoMarge" + d.getTime() + ".jpg");
try {
fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 150, fOut);
// getImageBitmap(myurl).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
Toast.makeText(MainActivity.this, "Photo Saved Sucessfully", 500).show();
// mDialog.dismiss();
// MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Photo Not Saved Sucessfully", 500).show();
}
}
});
i removed my misstake from code .Actually i am saving another bitmap instead saving and converting framelayout bitmap
File cacheDir;
frame.setDrawingCacheEnabled(true);
icon = Bitmap.createBitmap(frame.getDrawingCache());
Bitmap bitmap = icon;
// String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Date d=new Date();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Photo Art Camera");
else
cacheDir=MainActivity.this.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
File file = new File(cacheDir, "PhotoMarge"+d.getTime()+".jpg");
try {
fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fOut);
//getImageBitmap(myurl).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
count();
Toast.makeText(MainActivity.this, "Photo Saved Sucessfully", 500).show();
// mDialog.dismiss();
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "Photo Not Saved Sucessfully", 500).show();
}
}
});
you are compressing it with different argument make it to 100 or 120 it should work..
OutputStream fOut = new FileOutputStream(output);
merged.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
OR
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
save22.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File cacheDir;
Toast.makeText(Main.this, "Photo", 500)
.show();
Bitmap icon;
relativelayout.setDrawingCacheEnabled(true);
icon = Bitmap.createBitmap(relativelayout.getDrawingCache());
Bitmap bitmap = icon;
relativelayout.setDrawingCacheEnabled(false);
//File mFile1 = Environment.getExternalStorageDirectory();
Date d=new Date();
String fileName = d.getTime()+"mg1.jpg";
File storagePath = (Environment
.getExternalStorageDirectory());
File dest = new File(storagePath + "/CityAppImages");
if (!dest.exists()) {
dest.mkdirs();
}
File mFile2 = new File(dest, fileName);
sdpath= mFile2.getAbsolutePath();
Log.d("qqqqqqqqqqqqqqqqqqqqqqq", "zzzzzzzz" + sdpath);
try {
FileOutputStream outStream;
outStream = new FileOutputStream(mFile2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(Main.this, "Photo Saved Sucessfully", 500)
.show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Main.this, "Photo Not Saved Sucessfully",
500).show();
}

Categories

Resources