Image is not storing in internal memory - android

I am using this code to store image in internal storage but image is not saving in internal storage, instead it is storing in external storage with path : /storage/sdcard0/DCIM/CAMERA/IMG_2345.,jpg
private String saveToInternalMemory(Bitmap bitmap,String imgName){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File file = new File(getCacheDir(),"imageDirectory");
//File directory = cw.getDir("imageDirectory", Context.MODE_PRIVATE);
//File userDirectory = new File(directory,imgName);
File myPath = new File(file,imgName);
Log.e("path",myPath.getAbsolutePath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
Log.e("img_name",bitmap.toString());
}catch (FileNotFoundException e){}
catch (IOException e){}finally {
try {
fos.close();
}catch (IOException e){}
}
return myPath.getAbsolutePath();
}
Can someone please explain me what is the error?

Related

write image in external directory android

How to write image in phone directory. Directory is created but i could not write image in this folder. Here is my code .please check if i am doing something wrong thanks in advance.
Bitmap bitmap;
String directory = new_path; // I am getting path here of image like sdcard/0/emulated/image.jpg
String folder_name = "abc"
bitmap = BitmapFactory.decodeFile(directory);
iv_6.setImageBitmap(bitmap); // image displayed here but not saving in directory.
try {
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator +folder_name);
f.mkdirs();
FileOutputStream fo = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, fo);
fo.close();
}catch (Exception e)
{
e.printStackTrace();
}
public void savePng(Bitmap bitmap, String filePath) {
try {
File temp = new File(filePath);
FileOutputStream os = new FileOutputStream(temp + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Android Encrypt video file with Facebook conceal library

I want to encrypt video files stored in SD card
Environment.getExternalStorageDirectory()
I have found that Facebook conceal is good for encrypting large files. I have followed this tutorial Make fast cryptographic operations on Android with Conceal
Here is what i have done up to now.
Encryption method
public void encodeAndSaveFile(File videoFile, String path) {
try {
final byte[] encrypt = new byte[(int) videoFile.length()];
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(path, Context.MODE_PRIVATE);
File mypath = new File(directory, "en1");
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this), new SystemNativeCryptoLibrary());
if (!crypto.isAvailable()) {
return;
}
OutputStream fileStream = new BufferedOutputStream(
new FileOutputStream(mypath));
OutputStream outputStream = crypto.getCipherOutputStream(
fileStream, new Entity("Passwordd"));
outputStream.write(encrypt);
outputStream.close();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(WebViewActivity.this,"Encrypted",Toast.LENGTH_LONG).show();
}
Decryption method
private void decodeFile(String filename,String path) {
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this),
new SystemNativeCryptoLibrary());
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(path, Context.MODE_PRIVATE);
File file = new File(directory, filename);
try {
FileInputStream fileStream = new FileInputStream(file);
InputStream inputStream = crypto.getCipherInputStream(fileStream,
new Entity("Password"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(WebViewActivity.this,"Decrypted",Toast.LENGTH_LONG).show();
}
But this code throwing following error at the run time
java.lang.illegalArgumentException: File contains a path separator
Then i have changed "mypath: variable of encodeAndSaveFile to this
File mypath = new File(directory, "en1");
and "file" variable of decodeFile to this
File file = new File(directory, filename);
Then no errors but. Encryption is not happening. Please help to solve this or suggest correct method for video encryption with conceal lib.

Save music file to internal storage from sdacard

I have been trying to save the file ( soundtrack ) from sdcard to the internal storage.
I have already done so with the image with this code
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,Name+".png");
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);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Now this works well, creates a directory and saves my bitmap, but i want to do the same thing for the music file.
Also i want to know how to read that file ( use it in the app ).
I have used this code to read the bitmap
File f=new File(path,name+".png");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
P.S. the code i have tried, but doesn't seem to be producing the right copy:
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
}
Here is the code that worked for me:
private void saveToInternalStorage(String name){
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to your data
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
// Create imageDir
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
DeleteFile(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Hope it helps!

android save images to internal storage

I'm having problems implementing this code Saving and Reading Bitmaps/Images from Internal memory in Android
to save and retrieve the image that I want, here is my code:
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, + name + "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
and to retrieve(I don't know if I'm doing wrong)
#Override
protected void onResume()
{
super.onResume();
try {
File f = new File("imageDir/" + rowID, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and nothing happens so what should I change??
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I think Faibo's answer should be accepted, as the code example is correct, well written and should solve your specific problem, without a hitch.
In case his solution doesn't meet your needs, I want to suggest an alternative approach.
It's very simple to store image data as a blob in a SQLite DB and retrieve as a byte array. Encoding and decoding takes just a few lines of code (for each), works like a charm and is surprisingly efficient.
I'll provide a code example upon request.
Good luck!
Note that you are saving the pick as name + profile.jpg under imageDir directory and you're trying to retrieve as profile.jpg under imageDir/[rowID] directory check that.
I got it working!
First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So, if you want to create your own directory in your File Storage you can use somethibng like:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Else, if you want to create a sub directory in your default device DCIM folder and then want to view your image in a separate folder in gallery:
FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
//Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
//return;
print("file not created");
return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
fos= new FileOutputStream(new_file);
Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
Helper functions:
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Hope this helps!

How to list all files in a remote/server directory

I'm making an android application that requires me to download all of the images from a remote directory locally in the /files path of the app. I need to know how to get a list of all of the files (all images) in that directory so I can download them all to the phone. I found the code to list the files in a local directory, but I need to know how to do the same thing for a remote directory (the directory is an http directory that requires no login)
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
Also, I'm using this working code to download the images once I get the name of them in the directory.
private void storeImage(String filename)
{
FileOutputStream out = null;
try
{
URL url = new URL(Consts.IMAGES_BASE_URL + filename);
InputStream is = (InputStream) url.getContent();
Bitmap bm = BitmapFactory.decodeStream(is);
out = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
File file = new File(context.getFilesDir().toString(), filename);
out = new FileOutputStream(file);
if(isPNG(filename))//isPNG just parses out the extension
bm.compress(Bitmap.CompressFormat.PNG, 85, out);
else if(isJPG(filename))
bm.compress(Bitmap.CompressFormat.JPEG, 85, out);
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
out.flush();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Any help is appreciated

Categories

Resources