根据图片url获取bitmap对象,并保存至sd卡

 

2016年07月26日 14:57:46 阅读数:166更多

个人分类: android笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fought_feng/article/details/52035790

根据图片url获取bitmap对象

public static Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }
  • 1
  • 2
  • 3

有了图片bitmap,我们就可以通过setImageBitmap()设置图片了。 
ImageView.setImageBitmap(bitmap);

将bitmap保存为图片文件

这里返回的是URI,我们也可以通过setImageURI()设置图片。 
ImageView..setImageURI(uri);;

public static Uri saveImageBitmap(Context context, Bitmap bitmap,String imgname) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory()+"/Images");
            if (!dir.exists())
                dir.mkdirs();
            file = new File(dir, imgname);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                return Uri.fromFile(file);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            Toast.makeText(context, "请确认已经插入SD卡", Toast.LENGTH_SHORT).show();
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值