Reputation: 406
Here is my code when I am writing to the file
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
//program crashing here
File f = File.createTempFile(myUrl,null,MyApplication.getAppContext().getCacheDir());
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
And here is my code reading from the same file
Bitmap bitmap;
try
{
File f = new File(myUrl);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bitmapArr = new byte[bis.available()];
bis.read(bitmapArr);
bitmap = BitmapFactory.decodeByteArray(bitmapArr, 0, bitmapArr.length);
bis.close();
fis.close();
}
catch(Exception e)
{
bitmap = null;
}
The program is crashing at the creation of the temp file in the first chunk of code.
EDIT: I am getting a libcore.io.ErrnoException
Upvotes: 1
Views: 1593
Reputation: 406
UPDATE: I found the problem and fixed it, for anyone interested see below.
I changed it to use the openFileOutput(String, int), and openFileInput(String) methods, I should have done it this way right from the beginning.
The following is working code to decode an input stream from a url containing an image into a bitmap, compress the bitmap and store it into a file, and to retrieve said bitmap from that file later.
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
String filename = "file"
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
and
Bitmap bitmap;
try
{
String filename = "file";
FileInputStream fis = this.openFileInput(filename);
bitmap = BitmapFactory.decodeStream(fis);
fis.close();
}
catch(Exception e)
{
bitmap = null;
}
Upvotes: 1