🟣 Kotlin로 간단한 이미지 필터링 앱 구현

Kotlin 예제

중급 난이도
예제 타입
11/10 등록일

Kotlin로 간단한 이미지 필터링 앱 구현

중급
태그
예제 실습 프로젝트 이미지처리 필터링 안드로이드
## 프로젝트 개요
이미지 처리 기능을 포함하는 간단한 모바일 앱을 만들고, Kotlin의 라이브러리와 확장성을 활용해 다양한 필터를 적용할 수 있도록 구현합니다. 이 예제는 안드로이드 스튜디오에서 실행 가능하며, 실제 프로젝트에 적용 가능한 실용적인 코드입니다.

## 주요 기능
- 이미지 로딩 및 표시
- 기본 필터(블러, 블랙 & 화이트, 그레이스케일)
- 사용자 인터페이스 조작
- 에러 처리 및 로그 출력

## 사용 방법
1. 안드로이드 스튜디오에서 새 프로젝트 생성 후 이 코드를 `MainActivity.kt`에 붙여넣기
2. `res/drawable` 폴더에 이미지 파일을 추가하세요 (예: `sample.jpg`)
3. 앱 실행 후 이미지를 선택하고 필터 적용

## 확장 가능성
- 더 많은 필터 기능 추가 (컬러 인버스, 컨트라스트 조절 등)
- GPU 가속 이미지 처리를 위한 라이브러리 통합
- 이미지 저장 및 공유 기능 구현
코드 예제
// MainActivity.kt
package com.example.imagefilteringapp

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private lateinit var imageView: ImageView

    private val galleryLauncher = registerForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri ->
        if (uri != null) {
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
                applyFilters(bitmap)
            } catch (e: IOException) {
                Toast.makeText(this, "이미지 로드 실패", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        imageView = findViewById(R.id.imageView)
        
        // 갤러리에서 이미지 선택 버튼 클릭 이벤트
        findViewById<android.widget.Button>(R.id.selectImageButton).setOnClickListener {
            galleryLauncher.launch("image/*")
        }
    }

    private fun applyFilters(bitmap: Bitmap) {
        imageView.setImageBitmap(bitmap)

        // 블러 필터 적용
        findViewById<android.widget.Button>(R.id.blurButton).setOnClickListener {
            val blurredBitmap = blurImage(bitmap)
            imageView.setImageBitmap(blurredBitmap)
        }

        // 그레이스케일 필터 적용
        findViewById<android.widget.Button>(R.id.grayscaleButton).setOnClickListener {
            val grayBitmap = convertToGrayscale(bitmap)
            imageView.setImageBitmap(grayBitmap)
        }

        // 블랙 & 화이트 필터 적용
        findViewById< nad. blackAndWhiteButton).setOnClickListener {
            val blackWhiteBitmap = convertToBlackAndWhite(bitmap)
            imageView.setImageBitmap(blackWhiteBitmap)
        }
    }

    private fun blurImage(bitmap: Bitmap): Bitmap {
        // 실제 구현을 위해 라이브러리(예: OpenCV) 사용 권장
        return bitmap // 임시로 동일한 이미지 반환
    }

    private fun convertToGrayscale(bitmap: Bitmap): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val grayBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        
        for (y in 0 until height) {
            for (x in 0 until width) {
                val pixel = bitmap.getPixel(x, y)
                val r = (pixel shr 16 and 0xFF).toFloat()
                val g = (pixel shr 8 and 0xFF).toFloat()
                val b = (pixel and 0xFF).toFloat()

                // 그레이스케일 변환 (중심 가중치)
                val gray = (r * 0.299f + g * 0.587f + b * 0.114f).toInt()
                
                val grayPixel = (gray shl 16) or (gray shl 8) or gray
                grayBitmap.setPixel(x, y, grayPixel)
            }
        }
        return grayBitmap
    }

    private fun convertToBlackAndWhite(bitmap: Bitmap): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val blackWhiteBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        
        for (y in 0 until height) {
            for (x in 0 until width) {
                val pixel = bitmap.getPixel(x, y)
                val r = (pixel shr 16 and 0xFF).toFloat()
                val g = (pixel shr 8 and 0xFF).toFloat()
                val b = (pixel and 0xFF).toFloat()

                // 흑백 변환 (중심 가중치)
                val gray = (r * 0.299f + g * 0.587f + b * 0.114f).toInt()
                
                val blackWhitePixel = if (gray > 127) -1 else 0
                blackWhiteBitmap.setPixel(x, y, blackWhitePixel)
            }
        }
        return blackWhiteBitmap
    }
}

// activity_main.xml 예시:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/selectImageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지 선택" />

    <Button
        android:id="@+id/blurButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="블러 필터 적용" />

    <Button
        android:id="@+id/grayscaleButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="그레이스케일 필터 적용" />

    <Button
        android:id="@+id/blackAndWhiteButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="블랙 & 화이트 필터 적용" />

</LinearLayout>
등록일: 2025년 11월 10일 02:37
언어 정보
언어
Kotlin
카테고리
Mobile
인기도
#11
학습 팁
코드를 직접 실행해보세요
변수를 바꿔가며 실험해보세요
오류가 나도 포기하지 마세요
다른 예제도 찾아보세요