티스토리 뷰

종종 blur 효과를 쓰고 싶을 때가 있다. 예를 들면 다이얼로그의 뒷 부분을 blur 처리하고 싶을 때 등... 일단 blur라는게 어차피 수식으로 이미지를 필터링하는 것인데, 여기서는 RenderScript를 활용한 방법을 소개한다.

https://futurestud.io/blog/how-to-blur-images-efficiently-with-androids-renderscript/

위 링크에서 이미 코드가 다 나와있는데 조금만 부연 내용을 추가하자면, RenderScript는 support library에 추가되어 있으므로 v8까지 커버 가능하다. 클래스들을 import할 때 패키지를 맞춰서 import 해주도록 신경써주면 된다. 그리고 Android Universal Image Loader 라이브러리를 사용하는 경우 bitmap에 config가 없어서 예외가 발생하는 경우가 있다. 이 경우 예외처리를 해줘야 하는데, 웃기게도 Bitmap의 setConfig 함수나 reconfigure 함수는 API 레벨 19 이상부터 사용 가능하다. 그보다 아래 레벨에서는 새로 bitmap을 생성해줘야 한다. (제가 잘못 알고 있는거면 제보 부탁드립니다.) 아래의 코드는 그러한 예외들을 처리한 코드이다.


public static Bitmap blurBitmap(Context context, Bitmap bitmap, float blurRadius) {

    if (bitmap.getConfig() == null) {

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){

            bitmap.setConfig(Bitmap.Config.ARGB_8888);

        } else {

            bitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        }

    }


    // Let's create an empty bitmap with the same size of the bitmap we want to blur

    Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

    // Instantiate a new Renderscript

    RenderScript rs = RenderScript.create(context);


    // Create an Intrinsic Blur Script using the Renderscript

    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));


    //Create the in/out Allocations with the Renderscript and the in/out bitmaps

    Allocation allIn = Allocation.createFromBitmap(rs, bitmap);

    Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);


    //Set the radius of the blur

    blurScript.setRadius(blurRadius);


    //Perform the Renderscript

    blurScript.setInput(allIn);

    blurScript.forEach(allOut);


    //Copy the final bitmap created by the out Allocation to the outBitmap

    allOut.copyTo(outBitmap);


    //recycle the original bitmap

    bitmap.recycle();


    //After finishing everything, we destroy the Renderscript.

    rs.destroy();


    return outBitmap;

}



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday