StreamCorruptedException when reading Bitmap from SD card - android

I have a web service that returns a jpg. I read this jpg into a byte[], convert to a Bitmap, and save it to the SD card. The next time the user comes to this Activity, it will search the SD card to see if the image exists before hitting the web service.
However, the code that checks the SD card returns a StreamCorruptedException if the file exists.
Here is my code that writes to the SD card:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/images").mkdirs();
try {
File file = new File(root + "/images", Integer.toString(intImageId) + "m.jpg");
FileOutputStream os = new FileOutputStream(file);
Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray(image, 0, image.length);
theImageFromByteArray.compress(Bitmap.CompressFormat.JPEG, 80, os);
os.flush();
os.close();
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
}
}
Here is my code that checks the SD card for the existing image:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/images", Integer.toString(mImageId) + "m.jpg");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
mImage = (Bitmap)ois.readObject();
ois.close();
}
catch (Exception e) {
}
}
The exception happens during new ObjectInputStream(fis)

You cannot arbitrarily readObject() like this. writeObject() needs to be used in order for readObject() to detect a valid serialized object.

Related

FileNotFoundException although the text file exist (readable and writable)

I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

how to save multiple bitmaps fastly in android studio

I want to save bitmaps in the gallery.
Currently, I am using the following code:
public void saveBitmap(Bitmap output){
String filepath = Environment.getExternalStorageDirectory().toString() + "/Imverter/ImverterEffectedImage";
File dir = new File(filepath);
if(!dir.exists()){
dir.mkdir();
}
String fileName = "Imverter" + System.currentTimeMillis() + ".jpg";
File image = new File(dir, fileName);
try {
FileOutputStream fileOutputStream = new FileOutputStream(image);
output.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It saves one single bitmap efficiently, but in my app, I have to deal with multiple bitmaps, and this method results in the slow output.
I want to store every single bitmap in a different files.
Thanks in advance.

What is the phone storage in Android devices?

I can pass sdcard location to my adb command using
file:///sdcard/Android/screen.bmp
What is the equivalent string, if my file is saved in phone memory instead of sdcard, will it be
file:///phone/Android/screen.bmp
That isn't necessarily how you access things saved internally on your phone.
Keep in mind how you save an image to internal storage:
Bitmap bitmap = ______; //get your bitmap however
try {
FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
Log.e("Saving the bitmap",e.getMessage());
}
Now, to go read it, we just get the context, and call getFileStreamPath(filename) on it.
Bitmap retrievedImage;
String filename = "desiredFilename.png";
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
retrievedImage = BitmapFactory.decodeStream(fi);
} catch (Exception e) {
Log.e("Retrieving the image", e.getMessage());
}
You can read more about this here.

save and load from sdcard shows empty file

I have a layout where I have an Edit Text field where I enter my data.
I have 2 buttons.Save and Plot.
When I press save I want to save the data (in xls format) from edittext field and the current date in sd card.
When I press the plot ,I want to plot them.
To save data:
case R.id.savebtn:
savefunc();
break;
...
public void savefunc(){
//saving
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
try {
FileOutputStream fOut = new FileOutputStream(file);
DataOutputStream os = new DataOutputStream(fOut);
os.writeUTF(thedata);
os.writeUTF(mydate);
os.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
For reading:
public void readfunc(){
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
try{
FileInputStream fIn = new FileInputStream(file);
DataInputStream is = new DataInputStream(fIn);
String name = is.readUTF();
String content = is.readUTF();
is.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
and :
case R.id.savebtn:
savefunc();
break;
case R.id.graphicsbtn:
readfunc();
...
But the xls file asks me format , I choose UTF8 and it is empty.
If I leave it shows chinese characters.
I am not sure about the "reading" part of the code.
Read this documentation here have more information about save data to external storage and read it is:
Saving and Reading file from External storage
Ok, I found this and works fine!

Store Bitmap image to SD Card in Android

I am facing some strange problem with my android code,
I have an image in Bitmap variable and want to save that file to SD card.
I code as follow,
Bitmap IMAGE // Loaded from internet servers.;
try {
File _sdCard = Environment.getExternalStorageDirectory();
File _picDir = new File(_sdCard, "MyDirectory");
_picDir.mkdirs();
File _picFile = new File(_picDir, "MyImage.jpg");
FileOutputStream _fos = new FileOutputStream(_picFile);
IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos);
_fos.flush();
_fos.close();
Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, ex.getMessage(), 7000).show();
}
I am using Sony Experia Arc as my testing device, when the phone is connected to my computer, the code works nice, it stores image and also displays in gallery. But when I disconnect phone from my computer and test the app, it doesn't save picture and doesn't show any exception.
use this function
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Check this answer will give more details Android saving file to external storage
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**This Code Cover the Following Topics**
1. Save a bitmap Image on sdcard a jpeg
2. Create a folder on sdcard
3. Create every file Separate name
4. Every file save with date and time
5. Resize the image in very small size
6. Best thing image Quality fine not effected from Resizing
The following method is used to create an image file using the bitmap
public void createImageFromBitmap(Bitmap bmp) {
FileOutputStream fileOutputStream = null;
try {
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Capture/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
//Capture is folder name and file name with date and time
fileOutputStream = new FileOutputStream(String.format(
"/sdcard/Capture/%d.jpg",
System.currentTimeMillis()));
// Here we Resize the Image ...
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream); // bm is the bitmap object
byte[] bsResized = byteArrayOutputStream.toByteArray();
fileOutputStream.write(bsResized);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources