andorid中网络图片下载、保存以及在相册中显示

String picUrl=”http://img2.3lian.com/2014/f3/82/68.jpg”;//要保存的图片Url

Bitmap bitmap = getPicBitmap(picUrl);
savePicture(bitmap);// 保存图片到SD卡中的指定目录

1、根据图片的URL获取图片getPicBitmap(url);

/**
     * 从网络获取图片
     * 
     * @param url
     * @return
     */
    public Bitmap getPicBitmap(String url) {
        Bitmap bitmap = null;
        try {
            URL pictureUrl = new URL(url);
            InputStream in = pictureUrl.openStream();
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

2、把图片保存到本地(自己指定目录)

    @SuppressLint("SdCardPath")
    public void savePicture(Bitmap bitmap) {    
        String temps = Environment.getExternalStorageDirectory() + "/ceshi/";//文件目录名字
        String pictureName = temps + "ceshi" + bitmap.getGenerationId()
                + ".jpg";//文件名
        File tempFiles = new File(temps);
        // 判断某个文件是否存在
        if (!tempFiles.exists()) {
            tempFiles.mkdir();
        }

        File file = new File(pictureName);
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            toShowPic(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3、本地图片保存之后发广播,更新图片(若不发广播更新,只能在文件管理中查看)

/**
     * 发广播更新图库
     * @param file
     */
    private void toShowPic(File file) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        ShowBigPicActivity.this.sendBroadcast(intent);

    }

注意:获取网络图片过程不要在主线程中执行,否则程序会出现错误。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值