Crop/trim a JPG file with empty space with Java

后端 未结 2 1894
陌清茗
陌清茗 2020-12-16 02:42

Is there a framework which is able to remove the white space (rectangular) of an image. We create Image Thumbnails from technical drawings which are unfortunately in PDF for

2条回答
  •  盖世英雄少女心
    2020-12-16 03:26

    For Android users, here is an example using Mike Kwan Answer:

        public static Bitmap TrimImage(Bitmap bmp) {
        int imgHeight = bmp.getHeight();
        int imgWidth  = bmp.getWidth();
    
        //TRIM WIDTH
        int widthStart  = imgWidth;
        int widthEnd = 0;
        for(int i = 0; i < imgHeight; i++) {
            for(int j = imgWidth - 1; j >= 0; j--) {
                if(bmp.getPixel(j, i) != Color.TRANSPARENT &&
                        j < widthStart) {
                    widthStart = j;
                }
                if(bmp.getPixel(j, i) != Color.TRANSPARENT &&
                        j > widthEnd) {
                    widthEnd = j;
                    break;
                }
            }
        }
        //TRIM HEIGHT
        int heightStart = imgHeight;
        int heightEnd = 0;
        for(int i = 0; i < imgWidth; i++) {
            for(int j = imgHeight - 1; j >= 0; j--) {
                if(bmp.getPixel(i, j) != Color.TRANSPARENT &&
                        j < heightStart) {
                    heightStart = j;
                }
                if(bmp.getPixel(i, j) != Color.TRANSPARENT &&
                        j > heightEnd) {
                    heightEnd = j;
                    break;
                }
            }
        }
    
        int finalWidth = widthEnd - widthStart;
        int finalHeight = heightEnd - heightStart;
    
        return Bitmap.createBitmap(bmp, widthStart,heightStart,finalWidth, finalHeight);
    }
    

    Hope this help someone :)

    EDIT:

    Guys, I just updated my answer cuz last code was just trimming the end of the image, not the beginning. This one is working just great :)

提交回复
热议问题