Android 存储网络图片到SD卡,并且无网络状态时显示圆形头像

上一个项目完工有需求是要在无网络状态时能够加载名字和头像,名字好说,在SharedPreferences中存储后,判断无网络链接后就直接读取就行了,但头像需要存储在sd卡,一开始的构思是在onCreate方法中imageview在使用glide显示后再通过imageView的到bitmap然后存储到sd卡中

public static void saveBookpic(ImageView iv, String strLocalFile) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            //创建一个文件夹对象,赋值为外部存储器的目录
            File sdcardDir = Environment.getExternalStorageDirectory();
            //得到一个路径,内容是sdcard的文件夹路径和名字
            File file = new File(strLocalFile);//图片路径
            iv.setDrawingCacheEnabled(true);
            if (!file.exists()) {
                Bitmap bm = iv.getDrawingCache();
                BufferedOutputStream bos;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(file));
                    bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                    bos.flush();
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

但后来发现存储的一直是glide的占位的图片,因为oncreate方法没有执行完,glide的网络图片并没有显示出来,所以只能通过网络直接把网络资源存储在sd卡了,下面就是我的异步任务

 class SavePicURLAsync extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(图片网址);
            try {
                HttpResponse response = httpClient.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();

                    File f = new File(strLocalFile);//想要存储的本地路径
                    f.createNewFile();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(f);
                        byte[] buf = new byte[1024];
                        int length;
                        while ((length = is.read(buf)) != -1) {
                            fos.write(buf, 0, length);
                        }

                        is.close();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }

注意需要先判断一下有没有网络和sd卡中文件有没有存在哦,
对了,通常情况下头像都是圆形的,在网络情况下使用glide直接加载圆形图片需要使用glide 的bitmapTransform属性,我一直是这么使用

 Glide.with(mContext)
                .load(Picurl)//图片网址
                .error(R.mipmap.bookpic)//加载出错时显示的图片
                .placeholder(R.mipmap.bookpic)//加载中显示的图片
                .bitmapTransform(new CropCircleTransformation(mContext)).crossFade(1000)//图片转化为圆形
                .into(mimglearningBook);

CropCircleTransformation这个类我也忘了是哪个码神大大给的了,

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
/**
 * Created by Administrator on 2016/11/24 0024.
 */
public class CropCircleTransformation implements Transformation<Bitmap> {
    private BitmapPool mBitmapPool;
    public CropCircleTransformation(Context context) {
        this(Glide.get(context).getBitmapPool());
    }
    public CropCircleTransformation(BitmapPool pool) {
        this.mBitmapPool = pool;
    }
    @Override
    public Resource transform(Resource resource, int outWidth, int outHeight) {
        Bitmap source = resource.get();
        int size = Math.min(source.getWidth(), source.getHeight());
        int width = (source.getWidth() - size) / 2;
        int height = (source.getHeight() - size) / 2;
        Bitmap bitmap = mBitmapPool.get(size, size, Bitmap.Config.ARGB_8888);
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader =
                new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        source.recycle();
        if (width != 0 || height != 0) {
            // source isn't square, move viewport to center
            Matrix matrix = new Matrix();
            matrix.setTranslate(-width, -height);
            shader.setLocalMatrix(matrix);
        }
        paint.setShader(shader);
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return BitmapResource.obtain(bitmap, mBitmapPool);
    }
    @Override public String getId() {
        return "CropCircleTransformation()";
    }

}

这样就能加载圆形图片了,一开始脑子抽了一下,忘了glide也可以加载sd卡中的图片了,还想要自定义一个圆形imageView,

 if (!Tools.isNetworkConnected(mContext)) {//如果没网
            mtextlearingBook.setText(SharedPreferencesUtil.getSaveLearningBookName(mContext));
            Glide.with(mContext)
                    .load( Uri.fromFile( new File(图片网址) ) )
                    .bitmapTransform(new CropCircleTransformation(mContext)).crossFade(1000)//转化为圆形
                    .into(mimglearningBook);
        } else {
            new GetPredictTask().execute();
        }

这样就能在无网络状态加载已存在与sd卡的图片文件了

你可能感兴趣的:(存储)