Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
Add Comment
Please, Sign In to add comment