uri (url)保存为jpg图片(文件)

String uri = "http://192.168.1.108/onvifsnapshot/media_service/snapshot?channel=1&subtype=0"

这是一个图片地址:

1.没有以jpg或者png结尾

2.没有文件名

怎么保存为图片呢?困扰了我很久,下面是教程:

 

//通过URL保存图片
    public static void savePic(final String url,Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    //打开连接
                    URLConnection conn = imageurl.openConnection();
                    //打开输入流
                    InputStream is = conn.getInputStream();
                    //获得长度
                    int contentLength = conn.getContentLength();
                    //创建文件夹 MyDownLoad,在存储卡下
                    File file = new File(Config.sd_saveOnvifsnapshot_path);
                    //不存在创建
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    //下载后的文件名
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String fileName = Config.sd_saveOnvifsnapshot_path +
                            File.separator + dateFormat.format(new Date(System.currentTimeMillis())) + ".jpg";;
                    File file1 = new File(fileName);
                    if (file1.exists()) {
                        file1.delete();
                    }
                    //创建字节流
                    byte[] bs = new byte[1024];
                    int len;
                    OutputStream os = new FileOutputStream(fileName);
                    //写数据
                    while ((len = is.read(bs)) != -1) {
                        os.write(bs, 0, len);
                    }
                    //完成后关闭流
                    os.close();
                    is.close();

                    //下面这个是广播,使得保存的文件夹可以在Activity里面Toast提示出来,直接在里面Toast是无效的
                    //Intent msgIntent = new Intent(RtspPlayActivity.TAKE_PIC);
                    //msgIntent.putExtra("fileName", fileName);
                    //context.sendBroadcast(msgIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值