2012-04-17 14 views
46

Tengo un mapa de bits que deseo enviar al servidor codificándolo en base64 pero no quiero comprimir la imagen en png o jpeg.Conversión de mapa de bits a byteArray android

Ahora lo que estaba haciendo anteriormente era.

ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); 
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, byteArrayBitmapStream); 
byte[] b = byteArrayBitmapStream.toByteArray(); 
//then simple encoding to base64 and off to server 
encodedImage = Base64.encodeToString(b, Base64.NO_WRAP); 

ahora simplemente no desea utilizar ninguna compresión ni cualquier formato sin formato simple byte [] de mapa de bits que pueda codificar y enviar al servidor.

¿Alguna sugerencia?

Respuesta

123

Puede utilizar copyPixelsToBuffer() para mover los datos de píxeles a un Buffer, o puede utilizar getPixels() y luego convertir los enteros de bytes con el bit-desplazamiento.

copyPixelsToBuffer() es probablemente lo que usted desea utilizar, por lo que aquí es un ejemplo de cómo se puede utilizar:

//b is the Bitmap 

//calculate how many bytes our image consists of. 
int bytes = b.getByteCount(); 
//or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images. 
//int bytes = b.getWidth()*b.getHeight()*4; 

ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer 
b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer 

byte[] array = buffer.array(); //Get the underlying array containing the data. 
+2

pequeño código sería de gran ayuda :) –

+1

byte [] b; \t \t \t \t ByteBuffer byteBuffer = ByteBuffer.allocate (bitmapPicture.getByteCount()); \t \t bitmapPicture.copyPixelsToBuffer (byteBuffer); \t \t b = byteBuffer.array(); ??? –

+0

@AsadKhan He añadido un ejemplo. – Jave

5

en lugar de la línea siguiente en respuesta @jave:

int bytes = b.getByteCount(); 

utilizar la siguiente línea y función:

int bytes = byteSizeOf(b); 

protected int byteSizeOf(Bitmap data) { 
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { 
    return data.getRowBytes() * data.getHeight(); 
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { 
    return data.getByteCount(); 
} else { 
     return data.getAllocationByteCount(); 
} 
3
BitmapCompat.getAllocationByteCount(bitmap); 

es útil para encontrar el tamaño requerido de ByteBuffer

Cuestiones relacionadas