Created
September 23, 2018 01:33
-
-
Save liudongmiao/a2792d142cc412f4c57b8a72d5ec6b09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Bitmap; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.graphics.Rect; | |
/** | |
* Created by thom on 2018/9/23. | |
*/ | |
public class BitmapUtils { | |
static Bitmap crop(Bitmap bitmap) { | |
int width = bitmap.getWidth(); | |
int height = bitmap.getHeight(); | |
int left = 0; | |
int right = width; | |
int top = 0; | |
int bottom = height; | |
while (left < width) { | |
int pixel = bitmap.getPixel(left, height / 2); | |
if (Color.alpha(pixel) != 0) { | |
break; | |
} | |
left++; | |
} | |
while (right > 0) { | |
int pixel = bitmap.getPixel(right - 1, height / 2); | |
if (Color.alpha(pixel) != 0) { | |
break; | |
} | |
right--; | |
} | |
while (top < height) { | |
int pixel = bitmap.getPixel(width / 2, top); | |
if (Color.alpha(pixel) != 0) { | |
break; | |
} | |
top++; | |
} | |
while (bottom > 0) { | |
int pixel = bitmap.getPixel(width / 2, bottom - 1); | |
if (Color.alpha(pixel) != 0) { | |
break; | |
} | |
bottom--; | |
} | |
if (left == 0 && top == 0 && right == width && bottom == height) { | |
return bitmap; | |
} | |
Bitmap crop = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888); | |
Canvas canvas = new Canvas(crop); | |
Rect src = new Rect(left, top, right, bottom); | |
Rect dst = new Rect(0, 0, crop.getWidth(), crop.getHeight()); | |
canvas.drawBitmap(bitmap, src, dst, null); | |
return crop; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment