Android 예제 파일

Android 갤러리에서 가져온 이미지 DB에 저장, 불러오기

Kyung_Development 2024. 4. 2. 09:03

일단 Main 버튼 3개를 생상하여


각각의 기능을 추가한다

 

1번은 갤러리 2번은 DB에 저장하기 3번은 불러오는 소스 이다 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="갤러리 이동"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="goToGallery" />

    <Button
        android:id="@+id/button_save_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이미지 저장"
        android:layout_below="@id/button_gallery"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:onClick="saveImage" />

    <Button
        android:id="@+id/button_load_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이미지 불러오기"
        android:layout_below="@id/button_save_image"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:onClick="loadImage" />

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_load_image"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="20dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:visibility="gone" />

</RelativeLayout>

 

 

 

 

 

각각 버튼에 대한 동작 을 추가한다. 

 public void goToGallery(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_GALLERY);
    }

    public void saveImage(View view) {
        if (imageUri != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                dbHelper.insertImage(byteArray);
                Toast.makeText(this, "이미지가 저장되었습니다.", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "이미지 저장에 실패했습니다.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "이미지를 먼저 선택하세요.", Toast.LENGTH_SHORT).show();
        }
    }

    public void loadImage(View view) {
        byte[] byteArray = dbHelper.getImage();
        if (byteArray != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imageView.setImageBitmap(bitmap);
            imageView.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, "이미지가 없습니다.", Toast.LENGTH_SHORT).show();
        }
    }

 

 

SQLiteOpenHelper를 추가한다
 
 public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY,"
                + COLUMN_IMAGE + " BLOB"
                + ")";
        db.execSQL(CREATE_TABLE);
    }
 

기본적인 ID 값과 이미지만 추가하는 DB 이다

 

 

 

  public void insertImage(byte[] imageByteArray) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_IMAGE, imageByteArray);
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

 

이미지를 추가하는 소스 이다

 

 

 

 

 

    @SuppressLint("Range")
    public byte[] getImage() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_IMAGE}, null,
                null, null, null, null);
        byte[] imageByteArray = null;
        if (cursor != null && cursor.moveToFirst()) {
            imageByteArray = cursor.getBlob(cursor.getColumnIndex(COLUMN_IMAGE));
            cursor.close();
        }
        db.close();
        return imageByteArray;
    }

이미지 값을 가져오는 소스이다 


저 처럼 이미지를 저장하고 불러오는 페이지를 만드시는 분들에게 좋은 방법이 될 것 같아 작성했습니다.

 

:)