Android Bitmap save without transparent area

前端 未结 4 1937
暖寄归人
暖寄归人 2021-02-05 19:24

I want to save bitmap without transparent area.

Bitmap has large transparent pixel.

So i want to remove that

How can i do this?

I cant add pictur

4条回答
  •  猫巷女王i
    2021-02-05 19:46

    Crop transparent border with this github.

    public static Bitmap crop(Bitmap bitmap) {
    
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        int[] empty = new int[width];
        int[] buffer = new int[width];
        Arrays.fill(empty, 0);
        int top = 0;
        int left = 0;
        int bottom = height;
        int right = width;
    
        for (int y = 0; y < height; y++) {
            bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
            if (!Arrays.equals(empty, buffer)) {
                top = y;
                break;
            }
        }
    
        for (int y = height - 1; y > top; y--) {
            bitmap.getPixels(buffer, 0, width, 0, y, width, 1);
            if (!Arrays.equals(empty, buffer)) {
                bottom = y;
                break;
            }
        }
    
        empty = new int[height];
        buffer = new int[height];
        Arrays.fill(empty, 0);
    
        for (int x = 0; x < width; x++) {
            bitmap.getPixels(buffer, 0, 1, x, 0, 1, height);
            if (!Arrays.equals(empty, buffer)) {
                left = x;
                break;
            }
        }
    
        for (int x = width - 1; x > left; x--) {
            bitmap.getPixels(buffer, 0, 1, x, 0, 1, height);
            if (!Arrays.equals(empty, buffer)) {
                right = x;
                break;
            }
        }
    
        return Bitmap.createBitmap(bitmap, left, top, right - left + 1, bottom - top + 1);
    }
    

提交回复
热议问题