Android位图保存没有透明区域

我想保存没有透明区域的位图

位图具有大的透明像素。

所以我想删除

我怎样才能做到这一点?

我不能添加图片,所以用符号解释。

我不想裁剪function。 我希望使用filter

┌────────────────────────┐

│透明区域

│┌────────┐

│收成这个
└────────┘
└────────────────────────┘

Solutions Collecting From Web of "Android位图保存没有透明区域"

要查找位图的非透明区域,请在x和y中遍历位图,并查找非透明区域的最小值和最大值。 然后裁剪位图到这些坐标。

Bitmap CropBitmapTransparency(Bitmap sourceBitmap) { int minX = sourceBitmap.getWidth(); int minY = sourceBitmap.getHeight(); int maxX = -1; int maxY = -1; for(int y = 0; y < sourceBitmap.getHeight(); y++) { for(int x = 0; x < sourceBitmap.getWidth(); x++) { int alpha = (sourceBitmap.getPixel(x, y) >> 24) & 255; if(alpha > 0) // pixel is not 100% transparent { if(x < minX) minX = x; if(x > maxX) maxX = x; if(y < minY) minY = y; if(y > maxY) maxY = y; } } } if((maxX < minX) || (maxY < minY)) return null; // Bitmap is entirely transparent // crop bitmap to non-transparent area and return: return Bitmap.createBitmap(sourceBitmap, minX, minY, (maxX - minX) + 1, (maxY - minY) + 1); } 

用这个github裁剪透明边框。

 public Bitmap crop (Bitmap bitmap){ int height = bitmap.getHeight(); int width = bitmap.getWidth(); int[] empty = new int[width]; int[] buffer = new int[width]; Arrays.fill(empty,0); int top = 0; int left = 0; int botton = height; int right = width; for (int y = 0; y < height; y++) { bitmap.getPixels(buffer, 0, width, 0, y, width, 1); if (!Arrays.equals(empty, buffer)) { top = y; break; } } for (int y = height - 1; y > top; y--) { bitmap.getPixels(buffer, 0, width, 0, y, width, 1); if (!Arrays.equals(empty, buffer)) { botton = y; break; } } int bufferSize = botton -top +1; empty = new int[bufferSize]; buffer = new int[bufferSize]; Arrays.fill(empty,0); for (int x = 0; x < width; x++) { bitmap.getPixels(buffer, 0, 1, x, top + 1, 1, bufferSize); if (!Arrays.equals(empty, buffer)) { left = x; break; } } for (int x = width - 1; x > left; x--) { bitmap.getPixels(buffer, 0, 1, x, top + 1, 1, bufferSize); if (!Arrays.equals(empty, buffer)) { right = x; break; } } Bitmap cropedBitmap = Bitmap.createBitmap(bitmap, left, top, right-left, botton-top); return cropedBitmap; }