为什么decodeByteArray返回null?

时间:2015-08-31 15:56:51

标签: android image bitmap base64 android-camera

我正在尝试将图像保存到数据库并检索并在UI上显示它们。

我使用以下代码将点击的图片/从图库上传到My SQL。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Bitmap photo = null;
    if (requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK) {
        photo = (Bitmap) data.getExtras().get("data");
        // imageView.setImageBitmap(photo);



    }else if(requestCode == GALLERY_REQUEST && resultCode == getActivity().RESULT_OK) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getActivity().getContentResolver().query(
                selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();


        photo = BitmapFactory.decodeFile(filePath);
    }

}

以下代码将其上传到db。

 void createParam(){
     photo.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream);
     byte[] b = byteArrayBitmapStream.toByteArray();
     String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
     params.add(new BasicNameValuePair("image", encodedImage));
  }

此代码用于解码从db。

检索的图像字符串
public Bitmap getImage() {
        if("null".equalsIgnoreCase(image)){
            return null;
        }else{
        byte[] decodedString = Base64.decode(image, Base64.NO_WRAP);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,     decodedString.length);
    return decodedByte;
    }
}

问题是decodeByteArray在方法中返回null。字符串没有被解码。对于前置摄像头点击的图像,此问题不会发生。 请帮我找到问题!

1 个答案:

答案 0 :(得分:0)

我也得到了null,并通过设置options.inJustDecodeBounds=false;

对其进行了修复
public static String bitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}


public static Bitmap base64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds=false;
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length, opts);
}