Android Firebase : 이미지뷰의 bitmap을 firestorage에 저장 및 불러오기

용씨·2021년 8월 21일
0

[공경진] fillin-map

목록 보기
7/9

이미지뷰의 bitmap을 firestorage에 저장 및 불러오기

이미지뷰의 bitmap을 firestorage에 저장

onResume함수에 넣은 코드를 넣은 이유

지도가 있는 액티비티를 빠져나갈 때 지도의 이미지뷰들을 firestorage에 저장한다.

 @SuppressLint("WrongThread")
    override fun onResume() {
        super.onResume()
        val keySet = ClickedIMGS.keys
        for (name in keySet) {
            val imageView = ClickedIMGS[name]
            if (imageView != null && imageView.drawable is BitmapDrawable) {
                val bitmap = (imageView.drawable as BitmapDrawable).bitmap
                val baos = ByteArrayOutputStream()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, 100, baos)
                } else {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
                }
                val data = baos.toByteArray()
                // FirebaseStorage
                val storageRef = storage.reference
                // storage의 폴더는 자동 생성된다.
                val bitmapRef = storageRef.child("imageView/$uid/$name")
                val uploadTask: UploadTask = bitmapRef.putBytes(data)
                uploadTask.addOnFailureListener {
                    // Handle unsuccessful uploads
                    Log.d("uploadTask", "Faliure")
                }.addOnSuccessListener {
                    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                    Log.d("uploadTask", "Success")
                }
            }
        }
    }

WEP_LOSSLESS로 하면 에러가 나는 경우도 있어서 버전 차이를 추가했다.

firestorage에 저장한 파일 불러와 이미지뷰에 표시

 private fun uploadImageFromStorage() {
        val uidRef = storage.reference.child("imageView/$uid")
        uidRef.listAll()
            .addOnSuccessListener(OnSuccessListener<ListResult> { result ->
                for (fileRef in result.items) {
                    uidRef.child("${fileRef.name}").downloadUrl.addOnCompleteListener {
                        if (it.isSuccessful) { // ALLIMGS는 key가 string, 값이 imageView인 해시맵이다.
                        	Glide.with(this).asBitmap().load(it.result)
                                    .into(object :BitmapImageViewTarget(AllIMGS["${fileRef.name}"]) {});
                                   
                        }
                    }
                }
            })
            .addOnFailureListener(OnFailureListener {})
    }
profile
아침형 인간이 목표

0개의 댓글