How to save an image in Android without compressing? - java

I'm making an Android application that captures images and stores them in the internal memory, but to save the images are compressed and I want to be saved in its original size without any compression.
This is the code I am using to store images, as I do so not me compress ??
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, "TheChat" + (System.currentTimeMillis()/1000) + "Avatar.jpg");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Save it as a BLOB (bytearray), then reconvert it to a bitmap upon loading it. If it's for internal use only it should work fine. If you're not compressing it at all you might as well save it in a straight-forward format.

Related

Read and write bitmap to android fails

I am trying to write and read a bitmap following the suggestions on other topics about this, the thing is i never get the bitmap when i try to read on the path where i saved the image:
So i have this to write the bitmap:
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,"captured");
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.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
}
i pass the returned path to another activity and then i pass it as parameter to get the bitmap like this:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "captured.jpg");
Log.d("filehe",f.toString());
b = BitmapFactory.decodeStream(new FileInputStream(f));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
i feel i am doing something wrong here, but can't figure out what, the b variavel has no value :/.
Any help?
Thanks
So i have this to write the bitmap:
The file that you save is named captured.
i pass the returned path to another activity and then i pass it as parameter to get the bitmap like this
Here, you are trying to load captured.jpg, which is not captured.
You could avoid this sort of problem by having the first method return the File that the second method then uses.
Also:
Use an image-loading library (e.g., Picasso, Glide) that has an in-memory cache, so you do not waste the user's time re-loading the same bitmap from disk
Get rid of ContextWrapper from the first method, as you do not need it

My app can create a file, but cannot read it

I write a file in internal memory:
byte[] data = ... // (A buffer containing wav data)
String filename = context.getFilesDir().getAbsolutePath() + "/newout.wav";
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
Then I try to play it:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filename);
player.prepare();
player.setLooping(false);
player.start();
But the prepare() fails:
java.io.IOException: Prepare failed.: status=0x1
I checked the file and saw that it's permission is -rw-------. I changed it to -rw-r--r--, after that it was being played successfully.
So how come my app can write a file, but can't read it? And how can I make the FileOutputStream to set the permissions right?
To change programaticaly the file permissions to -rw-r--r-- you need to do smoething like this:
Process process = null;
DataOutputStream dataOutputStream = null;
try {
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
dataOutputStream.writeBytes("chmod 644 FilePath\n");
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
process.destroy();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
If you open a file, the default mode is Context.MODE_PRIVATE, e.g. as in
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
(taken from the documentation). Modes MODE_WORLD_READABLE and MODE_WORLD_WRITABLE are deprecated and do not work on newer devices. So I'd say you should rather write on the external storage to make contents available to other apps.
Note: as per documentation:
External storage:
"It's world-readable, so files saved here may be read outside of your control."

Convert encoded base64 image to File object in Android

I am trying to use the AndroidImageSlider library and populate it with images that I have downloaded as a base64 string.
The library only accepts URLs, R.drawable values, and the File object as parameters.
I am trying to convert the image string to a File object in order to be passed to the library function. I have been able to decode from base_64 and convert to a byte[] so far.
String imageData;
byte[] imgBytesData = android.util.Base64.decode(imageData, android.util.Base64.DEFAULT);
You'll need to save the File object to disk for that to work. This method will save the imageData string to disk and return the associated File object.
public static File saveImage(final Context context, final String imageData) {
final byte[] imgBytesData = android.util.Base64.decode(imageData,
android.util.Base64.DEFAULT);
final File file = File.createTempFile("image", null, context.getCacheDir());
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
fileOutputStream);
try {
bufferedOutputStream.write(imgBytesData);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
It creates a temporary file in your applications 'cache' directory. However, you are still responsible for deleting the file once you no longer need it.

How to save a file to a specific spot on the phone

I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);
Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}

File not found exception when writing away file in java (android)

I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException

Categories