Ryan Folz
Ryan Folz

Reputation: 43

Android: How to write a Bitmap to internal storage

I am making an app that gets images from a URL. I want to be able to store these images on the phone so that if the url is the same as before, the user won't have to wait for the image to load but instead the app will pull it up (as it has already been received once).

Here is my code right now:

            URL url2 = new URL("http://ddragon.leagueoflegends.com/cdn/5.9.1/img/champion/" + champ + ".png");
            InputStream is = new BufferedInputStream(url2.openStream());
            //Save is to file
            FileOutputStream fos = null;
            try {
                fos = context.openFileOutput("temp_file", Context.MODE_PRIVATE);
                int b;
                while( (b = is.read()) != -1){
                    fos.write(b);
                }
                fos.close();
            } catch (FileNotFoundException asdf) {
                asdf.printStackTrace();
            }
            bd = BitmapFactory.decodeStream(is);

However, there is no fos.write() for a Bitmap. Also, I'm not sure how to excess the file either.

Any help would be great :)

Upvotes: 1

Views: 444

Answers (1)

pathfinderelite
pathfinderelite

Reputation: 3137

The Bitmap class has a compress() method for writing to an OutputStream

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

This will compress the bitmap using PNG format, which is lossless, so you won't sacrifice image quality by doing the compression.

To access the file after it is written, use the decodeFile() method of BitmapFactory

Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);

Upvotes: 1

Related Questions