开发者

Android use cache for saving images

开发者 https://www.devze.com 2023-03-24 18:15 出处:网络
The basic idea is that: I\'m downloading encrypted image file from internet and start decrypting it. After it\'s done I want to save it to the cache (if this is the best way to do what I need) and th

The basic idea is that: I'm downloading encrypted image file from internet and start decrypting it.

After it's done I want to save it to the cache (if this is the best way to do what I need) and than load it in a lazy loading listview.

But for now I just want to test the showing image after decryption in an ImageView.

Here is the code I'm using :

package com.android.basetableview;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

public class BaseTableViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ImageView imgView = (ImageView) findViewById(R.id.imgView);

        Bitmap myBitmap = getBitmapFromURL("http://pu-twitter.netau.net/card1.png");
        imgView.setImageBitmap(myBitmap);
    }


    public static Bitmap getBitmapFromURL(String src) {
        Bitmap myBitmap = null;
            try {

                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                //Decryption
                try {
                Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
                IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

                InputStream input = connection.getInputStream();
                CipherInputStream cis = new CipherInputStream(input, cipher);
                FileOutputStream fos  = new File开发者_运维技巧OutputStream(
                           new File(Environment.getExternalStorageDirectory(), "card2_decrypted.jpg"));
                byte[] b = new byte[8];
                int i;

                while ((i = cis.read(b)) != -1) {
                  fos.write(b, 0, i);
                }
                fos.flush(); fos.close();
                cis.close(); input.close();


                //myBitmap = BitmapFactory.decodeStream(input);

                }
                catch(Exception e){
                    e.fillInStackTrace();
                    Log.v("ERROR","Errorchence : "+e);
                }

                return myBitmap;


            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
}

As you can see, I'm saving the decrypted image in sdcard, but the images that I'm using are small and maybe the cache will be better option. So if you guys can give me some advice how can I do that and which is the best way to save the images and then show them as a content in a ImageView.


OK you don't need to save the images:

    public static Bitmap getBitmapFromURL(String src) {
        Bitmap myBitmap = null;
            try {

                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                //Decryption
                try {
                Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
                IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

                InputStream input = connection.getInputStream();
                CipherInputStream cis = new CipherInputStream(input, cipher);


                myBitmap = BitmapFactory.decodeStream(cis);

                }
                catch(Exception e){
                    e.fillInStackTrace();
                    Log.v("ERROR","Errorchence : "+e);
                }

                return myBitmap;


            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
}


You need to use a ImageView to show the image. second the imageview can accept a Bitmap, a resource or an URI. but bitmap is the best because using an uri and resource means the decoding of the image before its placed happens in the ui thread which is not a good thing to do for images.

for setting the image bitmap, get the reference to your imageview in your layout and use

myImageView.setImageBitmap(myImageBitmap);

to get an image bitmap from SD card you can use BitmapFactory.decodeFile(); function for example. i usually decode images to bitmaps straight from the stream from the internet and then save the bitmap as file on SD. i believe thats a better solution.

File f = new File(cacheDir, filename);
        OutputStream outStream = new FileOutputStream(f);
        Bitmap bmp;
        bmp = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
        bmp.compress(Bitmap.CompressFormat.PNG, 90, outStream);

where i am using the function flushed input stream because of a bug in the url connection. see this link

as for a cache you can definitely use the sdcard. its a lot better than using the phones memory for that (thats the cache dir on the phone which fills the phone memory), you can just clear the sd cache by removing all the images in your cache folder onDestroy(). its simple. and if you like a in-Memory cache then use a hashMap, weakReference or a softReference map. i suggest for longer storage a hashMap but be careful with the memory consumption.

for "Lazy Loading" images see this link

0

精彩评论

暂无评论...
验证码 换一张
取 消