2014-10-10 3 views
0

pgm 형식의 base64Binary 문자열을 Android의 비트 맵으로 변환해야합니다. 그래서 저는 base64로 인코딩 된 일반적인 비트 맵을 가지고 있지 않습니다. base64binary-string은 XML 파일에서 가져 왔습니다.Android parse base64Binary pgm to Bitmap

<ReferenceImage Type="base64Binary" Format="pgm" WidthPX="309" HeightPX="233" BytesPerPixel="1" > NDY4Ojo9QEFDRUVHRklLTE9OUFFTU1VWV1hZWltZWVlZWlpbW1xdXmBgYmJjZGNlZWRkZGRlZmZnZ2ZnaWpqa21ub29ubm9vb3BwcHBxcHFyc3FzcnJzcnJydH[...]VlaW1xbWltcXFxcXFxd.

Pattern.compile("<ReferenceImage .*>((?s).*)<\\/ReferenceImage>"); 
... 
String sub = r; //base64binary string pattern-matched from xml file 
byte[] decodedString = Base64.decode(sub.getBytes(), Base64.NO_WRAP); //probably wrong decoding (needs to be ASCII to binary?) 
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); //always null due to wrong byte-array 

필자는 pgm 이미지가 일반적으로 ASCII (내 xml과 같은) 또는 이진 (0..255)으로 저장된다는 것을 알고 있다고 생각합니다. 또한 Base64.decode에는 내가 가지고있는 ASCII가 아닌 이진 형식이 필요하다고 생각합니다. 그러나 BitmapFactory.decodeByteArray은 디코딩 된 바이트 배열을 인식하지 못하고 null을 반환합니다.

그래서 유효한 비트 배열을 만들기 위해 내 base64binary-pgm-ASCII-string을 유효한 바이트 배열로 변환 할 수 있습니까?

답변

0

Base64 디코딩은 문제가 없다고 생각합니다. 그러나 안드로이드의 BitmapFactory은 아마도 PGM 형식을 직접 지원하지는 않습니다. 지원 방법을 잘 모르겠습니다 만, createBitmap(...) 팩토리 메소드 중 하나를 사용하여 Bitmap을 아주 쉽게 만들 수있는 것 같습니다.

헤더를 구문 분석하는 방법에 대한 자세한 내용은 my implementation for Java SE을 참조하십시오 (필요한 경우 ASCII 판독을 지원하는 클래스도 있습니다).

헤더가없고 XML에서 높이/너비를 가져올 수도 있습니다. 이 경우 dataOffset0입니다. 헤더 구문 분석 할 때

, 당신은 너비, 높이를 알고 경우 이미지 데이터가 시작됩니다 : 당신의 대답에 대한

int width, height; // from header 
int dataOffset; // == end of header 

// Create pixel array, and expand 8 bit gray to ARGB_8888 
int[] pixels = new int[width * height]; 
for (int y = 0; y < height; y++) { 
    for (int x = 0; x < width; x++) { 
     int gray = decodedString[dataOffset + i] & 0xff; 
     pixels[i] = 0xff000000 | gray << 16 | gray << 8 | gray; 
    } 
} 

Bitmap pgm = Bitmap.createBitmap(metrics, pixels, width, height, BitmapConfig.Config. ARGB_8888); 
0

감사합니다! 당신은 저를 해결했습니다!

코드에서 약간의 오류가 발견되었습니다. 색인 i는 초기화되거나 증가하지 않습니다. 코드를 수정하고 테스트 해 보니 여기에 내 코드가 있습니다 :

private static Bitmap getBitmapFromPgm(byte[] decodedString, int width, int height, int dataOffset){ 

    // Create pixel array, and expand 8 bit gray to ARGB_8888 
    int[] pixels = new int[width * height]; 
    int i = 0; 
    for (int y = 0; y < height; y++) { 
     for (int x = 0; x < width; x++) { 
      int gray = decodedString[dataOffset + i] & 0xff; 
      pixels[i] = 0xff000000 | gray << 16 | gray << 8 | gray; 

      i++; 
     } 
    } 
    Bitmap pgm = Bitmap.createBitmap(pixels, width, height, android.graphics.Bitmap.Config.ARGB_8888); 
    return pgm; 
}