2014-10-17 73 views
0

我想将捕获的图像转换为字节[]。当我使用相机捕获图像时,它会被捕获,预览也会显示,并且图像也会成功保存在我的外部存储上。但是,当我尝试转换预览图像时,它不会在字节数组中存储任何内容。 以下是我在手机上按下预览图像按钮时调用的方法。无法将位图图像转换为字节[]

public static void previewCapturedImage() { 
    try { 
     static ByteArrayOutputStream stream = null; 
     imgPreview.setVisibility(View.VISIBLE); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inSampleSize = 8; 
     final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options); 
     imgPreview.setImageBitmap(bitmap); 
     stream = new ByteArrayOutputStream(); 
     bitmap.compress(CompressFormat.JPEG, 100, stream); 
     byte[] byteArray = stream.toByteArray(); 

    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 
} 

回答

0

转换图像串&字节数组,使用以下短的代码。


ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
yourbitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
//this will convert image to byte[] 
byte[] byteArrayImage = baos.toByteArray(); 
// this will convert byte[] to string 
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT); 
0

检查以下工作代码。这包括质量调整也

/** 
* @param bitmap 
* @param quality 1 ~ 100 
* @return 
*/ 
public static byte[] compressBitmap(Bitmap bitmap, int quality) 
{ 
    try 
    { 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, quality, baos); 

     return baos.toByteArray(); 
    } catch (Exception e) 
    { 
     PrintLog.print(TAG, e.toString(), e); 
    } 

    return null; 
}