Snippets

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

Created by サトミツジムラ

File テーブル.kt Added

  • Ignore whitespace
  • Hide word diff
+public open class Item (
+
+    public open var image: ByteArray? = null
+
+) : Serializable, RealmObject() {}

File 保存.kt Added

  • Ignore whitespace
  • Hide word diff
+/**
+* 新規保存
+*/
+fun saveItem(context: Context,item: Item) {
+    Realm.getInstance(context).use { realm ->
+        realm.executeTransaction {
+            val saveItem = realm.createObject(Item::class.java)
+            saveItem.image = item.image
+        }
+    }
+}

File 画像をByteArrayに変換.kt Added

  • Ignore whitespace
  • Hide word diff
+/**
+* 画像データを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
+}

File 画像をImageViewに表示.kt Added

  • Ignore whitespace
  • Hide word diff
+fun setAddImage(uri: Uri) {
+    Glide.with(context).load(uri).override(150, 200).dontAnimate().into(imageView)
+}

File 端末から画像取得.kt Added

  • Ignore whitespace
  • Hide word diff
+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)
+        }
+    }
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.