Skip to content

Instantly share code, notes, and snippets.

@liudongmiao
Created September 23, 2018 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liudongmiao/a2792d142cc412f4c57b8a72d5ec6b09 to your computer and use it in GitHub Desktop.
Save liudongmiao/a2792d142cc412f4c57b8a72d5ec6b09 to your computer and use it in GitHub Desktop.
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