Guest User

Untitled

a guest
Sep 22nd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import android.graphics.Bitmap;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Rect;
  5.  
  6. /**
  7. * Created by thom on 2018/9/23.
  8. */
  9. public class BitmapUtils {
  10.  
  11. static Bitmap crop(Bitmap bitmap) {
  12. int width = bitmap.getWidth();
  13. int height = bitmap.getHeight();
  14. int left = 0;
  15. int right = width;
  16. int top = 0;
  17. int bottom = height;
  18.  
  19. while (left < width) {
  20. int pixel = bitmap.getPixel(left, height / 2);
  21. if (Color.alpha(pixel) != 0) {
  22. break;
  23. }
  24. left++;
  25. }
  26.  
  27. while (right > 0) {
  28. int pixel = bitmap.getPixel(right - 1, height / 2);
  29. if (Color.alpha(pixel) != 0) {
  30. break;
  31. }
  32. right--;
  33. }
  34.  
  35. while (top < height) {
  36. int pixel = bitmap.getPixel(width / 2, top);
  37. if (Color.alpha(pixel) != 0) {
  38. break;
  39. }
  40. top++;
  41. }
  42.  
  43. while (bottom > 0) {
  44. int pixel = bitmap.getPixel(width / 2, bottom - 1);
  45. if (Color.alpha(pixel) != 0) {
  46. break;
  47. }
  48. bottom--;
  49. }
  50.  
  51. if (left == 0 && top == 0 && right == width && bottom == height) {
  52. return bitmap;
  53. }
  54.  
  55. Bitmap crop = Bitmap.createBitmap(right - left, bottom - top, Bitmap.Config.ARGB_8888);
  56. Canvas canvas = new Canvas(crop);
  57. Rect src = new Rect(left, top, right, bottom);
  58. Rect dst = new Rect(0, 0, crop.getWidth(), crop.getHeight());
  59. canvas.drawBitmap(bitmap, src, dst, null);
  60.  
  61. return crop;
  62. }
  63.  
  64. }
Add Comment
Please, Sign In to add comment