图片下载及保存

  1. 确定文件的下载路径,context.getExternalFilesDir(“images”),即app外部存储的files路径,无须动态权限声明
  2. 创建URL对象,val url = URL(path),由图片的下载地址创建
  3. 通过url.openConnection()打开连接,获取连接对象
  4. 连接conn.connect()
  5. 获取输入流,val input: InputStream = conn.getInputStream()
  6. 创建输出流,准备写入val fos = FileOutputStream(out)
  7. 标准io操作,将读到的字节写入到文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
try {
val buf = ByteArray(1024)
var numRead: Int
fos.run {
while ((input.read(buf).also { numRead = it }) != -1) {
write(buf, 0, numRead)
}
flush()
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
input.close()
fos.close()
}

//保存图片到系统相册
/**
* Q以上保存到系统相册中
*/
private fun saveToPicture(name: String, file: File) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, name)
put(MediaStore.Images.Media.DESCRIPTION, "This is a alarm pic")
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.TITLE, "Image.jpg")
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/")
}
val external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val resolver = PlatinDriveApp.instance.contentResolver
val insertUri = resolver.insert(external, values)
var inputStream: BufferedInputStream? = null
var outputStream: OutputStream? = null
try {
inputStream = BufferedInputStream(FileInputStream(file))
insertUri?.let {
outputStream = resolver.openOutputStream(it)
}
outputStream?.run {
val buffer = ByteArray(1024 * 4)
var len: Int
while ((inputStream.read(buffer).also { len = it }) != -1) {
write(buffer, 0, len)
}
flush()
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
inputStream?.close()
outputStream?.close()
}
}