這實(shí)際并非libpng核心代碼的問題畸陡,是我們項(xiàng)目會用的包裝代碼存在的行為瀑凝。
我們的Android NDK項(xiàng)目中使用了libpng坦刀,在讀取一個(gè)顏色查找表圖像時(shí)愧沟,發(fā)現(xiàn)效果不對蔬咬,比iOS實(shí)現(xiàn)存在顏色偏差。從png.h看沐寺,版本為libpng version 1.2.33 - October 31, 2008林艘。在包裝libpng的代碼中,有這么一段特殊處理的代碼:
unsigned char *rgba = new unsigned char[width * height * 4]; //each pixel(RGBA) has 4 bytes
png_bytep *row_pointers = png_get_rows(png_ptr, info_ptr);
//unlike store the pixel data from top-left corner, store them from bottom-left corner for OGLES Texture drawing...
int pos = (width * height * 4) - (4 * width);
for (int row = 0; row < height; row++) {
for (int col = 0; col < (4 * width); col += 4) {
rgba[pos++] = row_pointers[row][col + 0] * row_pointers[row][col + 3] / 255; // blue
rgba[pos++] = row_pointers[row][col + 1] * row_pointers[row][col + 3] / 255; // green
rgba[pos++] = row_pointers[row][col + 2] * row_pointers[row][col + 3] / 255; // red
rgba[pos++] = row_pointers[row][col + 3]; // alpha
}
pos = (pos - (width * 4) * 2); //move the pointer back two rows
}
顯然混坞,這對圖像作了垂直鏡像(Flip Vertical)狐援,即第一行像素變成最后一行像素。而我提供的png圖像是RGB24究孕,上述代碼將返回錯誤的結(jié)果啥酱。
Input #0, png_pipe, from 'lookup_crenshaw.png':
Duration: N/A, bitrate: N/A
Stream #0:0: Video: png, rgb24(pc), 128x128, 25 tbr, 25 tbn, 25 tbc
將其修改為讀取RGB三通道值即可。
而使用UIImage(返回RGBA)或Android SDK的Bitmap類(返回ARGB)都是從左上角開始讀取圖像數(shù)據(jù)厨诸,故它們除了Alpha通道位置不同镶殷,RGB數(shù)據(jù)都相同。
值得注意的是泳猬,Bitmap的getPixels接口中有個(gè)stride參數(shù)批钠,如果是讀取整張圖像宇植,應(yīng)該傳遞圖像的寬度值得封,示例如下。
try {
InputStream = new FileInputStream("/storage/emulated/0/lookup_dark.png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
int[] argb = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(argb, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
int[] rgba = new int[bitmap.getWidth() * bitmap.getHeight()];
for (int row = 0; row < bitmap.getHeight(); ++row) {
int index = row * bitmap.getWidth();
for (int col = 0; col < bitmap.getWidth(); ++col) {
int srcARGB = argb[col + index];
rgba[col + index] = ((srcARGB & 0xFF000000) >> 24) + ((srcARGB & 0xFFFFFF) << 8);
}
}
} catch (Exception e) {
e.printStackTrace();
}