Android 크롭 기능 없이 이미지 자르기

2020. 6. 29. 09:32Android

반응형

Uri이미지를 가운데를 기준으로 w, h 크기 만큼 crop한다.

public Bitmap cropCenterBitmap(Uri uri, int w, int h) {
        Bitmap src = null;
        try {

             src = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(src == null)
            return null;

        int width = src.getWidth();
        int height = src.getHeight();

        if(width < w && height < h)
            return src;

        int x = 0;
        int y = 0;

        if(width > w){
            x = (width - w)/2;
        }


        if(height > h){
            y = (height - h) / 2;
        }

        int cw = w; // crop width
        int ch = h; // crop height

        if(w > width)
            cw = width;

        if(h > height)
            ch = height;

        return Bitmap.createBitmap(src, x, y, cw, ch);
    }
반응형