0
我正在研究一种方法来删除位图的透明边界。该方法如下所示:从位图中删除透明边界
private static final int STEP = 4;//Don't check all the pixel, only a sampling
private Bitmap clipTransparent(Bitmap image) {
int x1, x2, y1, y2;
final int width = image.getWidth();
final int height = image.getHeight();
for (x1 = 0; x1 < width - 1; x1 += STEP) {
if (checkColumn(image, x1)) {
break;
}
}
x1 = Math.max(0, x1 - STEP);
for (x2 = width - 1; x2 > x1; x2 -= STEP) {
if (checkColumn(image, x2)) {
break;
}
}
x2 = Math.min(width, x2 + STEP);
for (y1 = 0; y1 < height - 1; y1 += STEP) {
if (checkRow(x1, x2, image, y1)) {
break;
}
}
y1 = Math.max(0, y1 - STEP);
for (y2 = height - 1; y2 > 0; y2 -= STEP) {
if (checkRow(x1, x2, image, y2)) {
break;
}
}
y2 = Math.min(height, y2 + STEP);
try {
image = Bitmap.createBitmap(image, x1, y1, x2 - x1, y2 - y1);
} catch (Throwable t) {
t.printStackTrace();
}
return image;
}
private boolean checkColumn(Bitmap image, int x1) {
for (int y = 0; y < image.getHeight(); y += STEP) {
if (Color.alpha(image.getPixel(x1, y)) > 0) {
return true;
}
}
return false;
}
private boolean checkRow(int x1, int x2, Bitmap image, int y1) {
for (int x = x1; x < x2; x += STEP) {
if (Color.alpha(image.getPixel(x, y1)) > 0) {
return true;
}
}
return false;
}
它工作的很好,但速度并不像我希望的那样快。 代码的瓶颈是获取像素的颜色。
现在,我通过调用image.getPixel(x, y)
,但看着了Android的源代码,getPixel
检查索引读取该值并不会减慢代码下来(x>=0 && x<getWidth() && y>=0 && y<getHeight() && !isRecycled
)其他的东西......
有没有一种办法没有任何索引检查或其他无用的东西访问像素数据(当然无用)? PS:我已经试过使用getPixels(),它返回一个包含所有颜色的int数组。但图像很大,分配所有的内存触发一个GC ...结果是一个更慢的方法
问题是我需要只做一次操作,位图很大(1920x1080)。我无法重用2MB阵列 – Spotlight
使用更小的阵列并调用该方法几次。 –
我会试试看,谢谢 – Spotlight