图像到Base64不能正常工作

时间:2016-03-11 07:19:46

标签: android imageview base64

大家好我从摄像机捕获图像并将其转换为Base64字符串,但是它没有提供正确的Base64字符串,只有大约20%的图像我只能看到使用Base64字符串,在ActivityResult上我可以在ImageView中查看完整的图像查看我的代码

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK && data != null) {

        try {

            Bitmap bp = (Bitmap) data.getExtras().get("data");
            img.setImageBitmap(bp);
            imgStr = bitmapToBase64(bp);

        } catch (Exception e) {
            e.printStackTrace();
            Log.d(LOGTAG.logTag, "Error due to : " + e.getMessage());
        }
    }
}


private String bitmapToBase64(Bitmap bitmap) {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    String encodedBitmap = Base64.encodeToString(byteArray, Base64.DEFAULT);

    Log.d(LOGTAG.logTag, "" + encodedBitmap);

    return encodedBitmap;

}

这件事让我发疯,任何指导都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

Actually when you capture a image from camera the image is not returned in Activity result you get null there so you try this.


/**
     * This method set the path for the captured image from camera for updating
     * the profile pic
     */
    private Uri getOutputMediaFile() {

        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory(), "."
                + Constants.CONTAINER);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            mediaStorageDir.mkdirs();
        }

        File mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + System.currentTimeMillis() + ".png");
        Uri uri = null;
        if (mediaFile != null) {
            uri = Uri.fromFile(mediaFile);

        }
        return uri;
    }

    call cameraIntent:-

 Intent intent = new Intent(Constants.CAMERA_INTERNAL_CLASS);
fileUri = getOutputMediaFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        /* start activity for result pass intent as argument and request code */
        startActivityForResult(intent, requestCode);

         @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK) {
           try
           {
           String path = fileUri.getPath();

          BitmapFactory.Options options = new BitmapFactory.Options();

        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
            img.setImageBitmap(bmp);
        imgStr = bitmapToBase64(bmp);
           }catch(Exception e)
           {}

            }
        } 
    }