본문 바로가기
안드로이드 자바

[Android][Java] 이미지 필터 만들기

by teamnova 2023. 10. 15.

오늘은 

비트맵 합치기
https://stickode.tistory.com/948

사람 배경 만들기

https://stickode.tistory.com/949

에 이어서 필터만들기를 해보겠습니다. 코드에 사용된 코드에 대한 설명은 위에 글들에 있으니 한번씩 보고 와주세요 ㅎ

 

먼저 java 코드입니다.

MainActivity
public class MainActivity extends AppCompatActivity {

    // 필요한 뷰 및 비트맵 변수 선언
    ImageView imageView, imageView3; // 이미지뷰 변수 선언
    Bitmap bitmap1; // 비트맵 변수 선언
    Button ImageCover; // 버튼 변수 선언

    // 액티비티 생성 시 호출되는 메서드
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 레이아웃 설정
        setContentView(R.layout.activity_main);

        // 뷰와 버튼 초기화
        imageView = findViewById(R.id.imageView); // imageView에 레이아웃에서 정의한 뷰 연결
        imageView3 = findViewById(R.id.imageView3); // imageView3에 레이아웃에서 정의한 뷰 연결
        ImageCover = findViewById(R.id.ImageCover); // ImageCover에 레이아웃에서 정의한 버튼 연결

        // 첫 번째 이미지뷰에 비트맵 설정
        bitmap1 = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.img_3); // 비트맵을 이미지 리소스에서 로드
        imageView.setImageBitmap(bitmap1); // imageView에 비트맵 설정

        // 버튼에 클릭 리스너 등록
        ImageCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 첫 번째 이미지뷰에서 비트맵을 가져옴
                BitmapDrawable drawable1 = (BitmapDrawable) imageView.getDrawable();
                Bitmap dst = drawable1.getBitmap();

                // 새로운 비트맵 생성 (크기는 원본 이미지와 동일)
                Bitmap segmentedBitmap = Bitmap.createBitmap(dst.getWidth(), dst.getHeight(), Bitmap.Config.ARGB_8888);

                // 두 번째 이미지뷰에서 비트맵을 가져옴
                BitmapDrawable drawable2 = (BitmapDrawable) imageView.getDrawable();
                Bitmap dst_ = drawable2.getBitmap();

                // 필터 색상 배열 생성
                int[] fliterColor = filterColors(dst_.getWidth(), dst_.getHeight());

                // 필터된 비트맵 생성
                Bitmap filterBitmap = Bitmap.createBitmap(fliterColor, dst_.getWidth(), dst_.getHeight(), Bitmap.Config.ARGB_8888);

                // 캔버스 생성하여 이미지를 그림
                Canvas canvas = new Canvas(segmentedBitmap);
                Paint paint = new Paint();
                canvas.drawBitmap(dst_, 0, 0, paint);

                // 필터링된 이미지를 SRC_OVER 모드로 그림
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
                canvas.drawBitmap(filterBitmap, 0, 0, paint);

                // 두 번째 이미지뷰에 필터링된 이미지 설정
                imageView3.setImageBitmap(dst_);
                imageView3.setImageBitmap(segmentedBitmap);
            }
        });
    }

    @ColorInt
    private int[] filterColors(int maskWidth, int maskHeight) {
        @ColorInt int[] colors = new int[maskWidth * maskHeight];
        for (int i = 0; i < maskWidth * maskHeight; i++) {
            // 색상 배열을 색상 값으로 초기화 (투명도: 128, 빨강: 255, 녹색: 0, 파랑: 255)
            colors[i] = Color.argb(128, 255, 0, 255);
        }
        return colors;
    }
}

layout xml 코드입니다.

activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />
    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        tools:srcCompat="@tools:sample/avatars" />
    <Button
        android:id="@+id/ImageCover"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="필터"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

결과물입니다.