一、java 里面使用下面的代码使用 bitmap.setPixel逐个写像素点数据,发现程序卡顿很严重。
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = y * width + x;
bitmap.setPixel(x, y, rgbaArray[index]);
}
}
二、然后写了下面的代码,对比一下使用setPixel 和setPixels耗费的时间,发现差距惊人,相差三百多毫秒。
public static void saveRgbaArrayAsJpeg(int[] rgbaArray, int width, int height, String filePath) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
long startTime = System.currentTimeMillis();
for (int x = 0; x < width; x++) {
int index = y * width + x;
bitmap.setPixel(x, y, rgbaArray[index]);
}
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
Log.d(TAG,"setPixel total cost time: " + duration + " ms");
startTime = System.currentTimeMillis();
bitmap.setPixels(rgbaArray, 0, width, 0, 0, width, height);
endTime = System.currentTimeMillis();
duration = endTime - startTime;
Log.d(TAG,"setPixels total cost time: " + duration + " ms");
File file = new File(filePath);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}