How to remove a border with an unknown width from an image

后端 未结 4 1815
渐次进展
渐次进展 2021-01-16 01:53

I\'m trying to build a program which can remove an single-colored border form an image.

The border is always white but the width of the border on the left and right

4条回答
  •  感情败类
    2021-01-16 02:28

    Perhaps not the best use of the APIs to find a solution, but the one that came to mind: directly modify the image's pixels.

    You can get a Bitmap's pixels with getPixels() and then create a new, cropped Bitmap with createBitmap(). Then, it's just a matter of finding the dimensions of the border.

    You can find the color of the border by accessing the pixel located at position 0, and then compare that value (an int) to the value of each proceeding pixel until your reach the border (the pixel that isn't that color). With a little bit of math, it can be done.

    Here is some simple code that demonstrates the point:

    private void cropBorderFromBitmap(Bitmap bmp) {
        int[] pixels;
        //Load the pixel data into the pixels array
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    
        //Convenience variables
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int length = pixels.length;
    
        int borderColor = pixels[0];
    
        //Locate the start of the border
        int borderStart;
        for(int i = 0; i < length; i ++) {
            if(pixels[i] != borderColor) {
                borderStart = i;
                break;
            }
        }
    
        //Locate the end of the border
        int borderEnd;
        for(int i = length - 1; i >= 0; i --) {
            if(pixels[i] != borderColor) {
                borderEnd = length - i;
                break;
            }
        }
    
        //Calculate the margins
        int leftMargin = borderStart % width;
        int rightMargin = borderEnd % width;
        int topMargin = borderStart / width;
        int bottomMargin = borderEnd / width;
    
        //Create the new, cropped version of the Bitmap
        bmp = createBitmap(bmp, leftMargin, topMargin, width - leftMargin - rightMargin, height - topMargin - bottomMargin);
    }
    

    This is untested and lacks error checking (e.g., what if the width is 0?), but it should serve as a proof-of-concept.

    EDIT: I just realized that I failed to complete the getPixels() method. The wonders of testing your code... it's fixed now.

提交回复
热议问题