ツジムラ サトミ Realmで画像保存

Created by ツジムラ サトミ
1
2
3
4
5
public open class Item (

    public open var image: ByteArray? = null

) : Serializable, RealmObject() {}
/**
* 新規保存
*/
fun saveItem(context: Context,item: Item) {
    Realm.getInstance(context).use { realm ->
        realm.executeTransaction {
            val saveItem = realm.createObject(Item::class.java)
            saveItem.image = item.image
        }
    }
}
/**
* 画像データをByteArrayに変換する
*/
fun createImageData() : ByteArray {
    val bitmap = (imageView.drawable as GlideBitmapDrawable).bitmap
    val baos = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
    val imageByteArray = baos.toByteArray()
    return imageByteArray
}
1
2
3
fun setAddImage(uri: Uri) {
    Glide.with(context).load(uri).override(150, 200).dontAnimate().into(imageView)
}
override fun getItemImage() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
    intent.addCategory(Intent.CATEGORY_OPENABLE)
    intent.setType("image/*");
    startActivityForResult(intent, RESULT_PICK_IMAGEFILE);
}
    
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    returnFlg = true
    val createItemView = findViewById(R.id.view_create_item) as CreateItemView
    if (requestCode == RESULT_PICK_IMAGEFILE && resultCode == RESULT_OK) {
        if (data != null) {
            val uri = data.data
            createItemView.setAddImage(uri)
        }
    }
}

Comments (0)