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
|
class ImageLoader {
companion object {
fun calculateInSampleSize(
options: BitmapFactory.Options,
reqWidth: Int,
reqHeight: Int
): Int {
// Raw height and width of image
val (height: Int, width: Int) = options.run { outHeight to outWidth }
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val halfHeight: Int = height / 2
val halfWidth: Int = width / 2
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
inSampleSize *= 2
}
}
return inSampleSize
}
fun decodeSampledBitmapFromResource(
ist: InputStream,
url: String,
reqWidth: Int,
reqHeight: Int
): Bitmap? {
// First decode with inJustDecodeBounds=true to check dimensions
return BitmapFactory.Options().run {
inJustDecodeBounds = true
BitmapFactory.decodeStream(ist, null,this)
// Calculate inSampleSize
inSampleSize = calculateInSampleSize(this, reqWidth, reqHeight)
// Decode bitmap with inSampleSize set
inJustDecodeBounds = false
BitmapFactory.decodeStream(URL(url).openStream(), null,this)
}
}
}
}
|
calculateInSampleSize
- 비트맵으로 사용할 이미지 크기를 지정한 값을 받음
- 2의 지수 비율만큼(2 -> 4 -> 8 -> 16) 지정한 값보다 작아질 때까지 나눔
- 4일 경우 가로 세로 길이가 1/4이 되어 메모리가 1/16로 줄어듦
decodeSampledBitmapFromResource
- BitmapFactory.Options : 디코딩 옵션을 추가하는 클래스
- inJustDecodeBounds : 메모리 할당을 피하여 null인 비트맵 개체를 반환하지만 outwidth, outheight, outMimeType을 설정할 수 있음. 이 기법을 사용하면 비트맵을 생성(메모리 할당 포함)하기 전에 이미지 데이터의 크기와 유형을 읽을 수 있음
- decodestream() : url의 이미지를 inputstream에 넣음
이미지 소스에 맞게 알맞은 decode 메서드 선택할 것
Inputstream은 한 번 사용하면 재사용이 불가능 하므로 다시 decodestream을 하려면 새로운 url로부터 재생성해야 함
https://developer.android.com/topic/performance/graphics/load-bitmap?hl=ko
큰 비트맵을 효율적으로 로드 | Android 개발자 | Android Developers
이미지의 모양과 크기는 다양합니다. 많은 경우 이미지는 일반적인 애플리케이션 사용자 인터페이스(UI)에서 요구하는 크기보다 큽니다. 예를 들어, 시스템 Gallery 애플리케이션은 Android 기기의 카메라를 사용하여 촬영한 사진을 표시하는데 일반적으로...
developer.android.com
'안드로이드' 카테고리의 다른 글
안드로이드 Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 에러 해결 (0) | 2020.08.21 |
---|---|
EditText 키보드 완료 버튼 이벤트 - Kotlin (0) | 2020.06.30 |
안드로이드 에러 : Static interface methods are only supported starting with Android N (--min-api 24) 해결 (0) | 2020.01.31 |
안드로이드 This version of Android Studio cannot open this project 에러 (0) | 2020.01.16 |
안드로이드 ANR (0) | 2020.01.13 |