从图库中获取图像并转换为base64问题

时间:2017-01-23 07:18:07

标签: android bitmap android-gallery

对不起要问愚蠢的问题。但它解决了我的me.please帮助我尝试了stackoverflow上的所有代码并遵循其他教程但它根本没有帮助。我正在从galary中获取图像并转换为base64它完美地工作当在相机上拍摄图像但为什么它不工作时我不知道请帮帮我。(

这是选择图像的代码

private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library",
                "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(TestFragment.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result= Utility.checkPermission(TestFragment.this);

                if (items[item].equals("Take Photo")) {
                    userChoosenTask ="Take Photo";
                    if(result)
                        cameraIntent();

                } else if (items[item].equals("Choose from Library")) {
                    userChoosenTask ="Choose from Library";
                    if(result)
                        galleryIntent();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

在此之后

 private void galleryIntent()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
    }

    private void cameraIntent()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
    }

    private void onCaptureImageResult(Intent data) {
        bitmap = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");

        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        imgvcomp.setImageBitmap(bitmap);

        String img=getStringImage(bitmap);

        Log.v(TAG,"base64"+img);//perfectly string base64 to image


    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {


        if (data != null) {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        imgvcomp.setImageBitmap(bitmap);
        String img=getStringImage(bitmap);

          Log.v(TAG,"base64"+img);//checking in log base64 string to image cropeed image found

    }




    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        byte[] imageBytes = baos.toByteArray();

        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }
    private void showToastMessage(String message) {
        Log.v(TAG, String.format("showToastMessage :: message = %s", message));
//        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }

为什么我从galary中选择后找到裁剪后的图像?错误日志中没有错误,这里是logcat

  E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/
 W/FlurryAgent: Flurry session paused for 
1 and remote module com.google.android.gms.tagmanager:8
 Selected remote version of com.google.android.gms.tagmanager, version >= 8
No container asset found in /assets/containers. Checking top level /assets directory for container assets.
 Tag Manager's event handler WILL NOT be installed (no container loaded)
 Tag Manager initilization took 274ms
Using measurement service
Connecting to remote service
 Connected to remote service
 Processing queued up service tasks: 1
 Suspending all threads took: 25.809ms
 V/help: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
                                                              CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
                                                              FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAzABywDASIA
                                                              AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
                                                              AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
                                                              ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
                                                              p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
                                                              AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
                                                              BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
                                                              U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
                                                              uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD6T2jo
                                                              BtXg/jUj87uDyOn9aY6+VyxBHqOaI33xkjO04wOlcCaa0NdVuhOhYMuZDxjOCaaCR/sntmnSdQeS
                                                              RjDUqReaSQQPr1BprXca0EAJUjnPr701UBIUdBz604KEQlgNuT34NP4LDbjHX0P0pLQaZGFBDNjg
                                                              dAfWkCEsC/Bx25qQcZB6n06CmkHIY4Kjj3rO+40roiW3VMEsWcc7j1P9KmAyS2BnGTnmm71kOR0B
                                                              OTT1GUJB46Y7mpauFrsjU9AFyewpXwgOAATyccCl2b8HoR07ZpCCASQCT171SJvYYwCspC/XNI2B
                                                              kHtTpFGdoBJ44PY0sjDnocdhT6FJJjDCu0+h79zTHQBtwXn1/wAal24O4cA0igK5B5HfHSnuSmNL
                                                              HDdAQPrimlgdueFGD7U5QccgsCcAinMMlflGBwc96SEN5BYlsgngD+dIS7E4wQOoJp6rllZQFPUA
                                                              +lN8lmYHOF65Hf8ACmnYLkWBkEZHocZoiTYSrDO4dAcjNTMpJO3Bx6VHs2Fjzk9qpAIQCuAAAvpS
                                                              BOOVyBzmpDCQCFIye5/nSnAU87ccY7UrWBDOO5z605W2ggqGPbPFKIlIHrjihIuCTgsRgjHeloBH
                                                              AgSOQ9MnPFPBLNkcZAwTTUI/4CvT1pfvA8Ej16GnrYAWIKAq4A5OPSlWLaGZsbunFEZCqMnOMY4p
                                                              /wB5icYPv0poLCR7UjIb6ipFTy0O1iQTnFKuTnGBihApJUjJPY07id+hNtxuGcjAPBzTApBDAAkk
                                                              AU0KifPtBGduRUqoPm4LAc5IxQK6Y54zIWfJDcDPWoWYK46gE/nVpAQAvU9c5xVe5QrgZwTk5x0q
                                                              OuoX7D1jXqpwew6imxBgoBOSOQcYFELErtOOMYFK4by2y20cHj0pD8iN+GaM5Ljn6CidCygLgngY
                                                              7AU/fj5QOvQnqaUkgENwxxxmgFoiAny8bhlemaR025wCec5qfcEBB5OM+tMIDdz7EcYp9R2voRY2
                                                              Pwu52HQnggU5R5ZbIwpwSOtSLBlCWO1hzxQGOSCPl6VS12I13I8jaw6kcgU3LtDjLLnk55zipWiJ
                                                              LEYK9MdxTY8KG3NgHovqaqL0E0kMCs67zgEce9KCxVvnLfyFPDEKQFCjt70Fi2AFwQPmC8k0nqIY
                                                              rKTk8joSehoXMgJA4HQ9ARSxnb838AIC5GAfw9KkDndzk454HWl0AYhEgLcYGM/4ih1yxDAZx16i
                                                              lWNZGDL93sf6f/Wp5RScjg8DHXFVEBFGFxkHHPPUUY24yxNATc3Ulh1HamvtHfk9u9VF6CtcXZ1O
                                                              SR1weDTUAAYKM4PboKVs8L1B/A4pqnBODge4qxIdu3qTxg8EH1qMruyByR3AqQPgMQCPYc0iAbWb
                                                              OCeATS3HsIoUgE8k8HPpQVIkBOPL6be9IMbwNpy3IGeBSh8Io2ggHips+4hXCtuCk7icH3rD8Trj
                                                              T5lBwduP/rVvF1aMgA5HrwRXPeLH8uzcDkFce59qol7HxJ+0OHlvJVQKXXcFkxnGTyMccZA7814b
                                                              eRN54YqofABYDGQPT+te1/HaZP8AhJH864cRsDEqqMquOSevU46+2O1eM3EHmSrKHfywCAFGR14P
                                                              48/rXp0VZWv5/eckm7tldLdigkwIwfukjg+tVJJftbPJ1kXC9O3QcVYTa65+bd12vkHr6UQfPNLK
                                                              ibAOdu44Qeg9j3yeuKwvyvXuU2t0QLtMbq2WBOSp4GR3+vvUcscakFhkkY6ckfzqyMrAc4eTOVAG
                                                              M88/lVZlE8yv1Kc5JwPr+FVp0VhWGS/v22Sg4AyGXrx0z/nNNDNIxITkYBJOMemB6e9TxoTnJAGc
                                                              56j2piA4AOC7HgZ4GO+a1t7trgtBPKkBUlf3i8Njkn0J9/p7UfvI2dxgcDBIyFNS27YkKnBKDOc5
                                                              P4etP+a6Rgilmz93vmmnqmtDNvQsWkjGVQHZoyo3MqknnqcdeP8A69fU/wCzjpaFbW3TKIhXAI5X
                                                              /OMYr5f8OwGSd48Ha5ByDgr6kHrnvxX2P+zXZGSK1lRsKpyCwJOAcZyefT360TSUWKLu7n03Yrsg
                                                              WJW3YAwenHv71biQ+UQWCk9R1/Gq8EKrGdo2ggfN3NSnnK4ORwK827aOlK1iePptJDYPB9qmVOBg
                                                              k47dKrxIxUYAVx1BqxGrBcuwBAySOAPekbJaCkAYPAPXFNb943Iz3wPX1oT75OST69frQsLKWPAJ
                                                              PXrQMVSCDjBI7npSLyCWII7ZGcUOp+7yoPJxSgAjgEjON3SnfSwxfLwBg4Hr60u8cMuQem00zZwV
                                                              AyO4zSqrB85zxwaaABFtWQABR6DqKI02IF3Z7+1LjqSTkfrR8+AcbB6NyT9K0uwsABQsDgkjHH+f
                                                              1qGWPGWJzgd+uPepm+6R9PYgVA8gWNySGx044rJkO6Z518VLhbfS5nBBGCMZ56HB+gr8/vihcTX2
                                                              vX7kIwYgIynAwMtz2yNx6dPrmvtf47eIYtJ0m6lmPkoMhsDJUAZJA9gDkV8L+LbndLJ5oLbpCwwP
                                                              ckE9u9englyxb7/53OWsrtHB3UgiXfvPJw3YD/OKgub4shEZ5HO1sjn1rYkMc7yBYiy4wGbgZ7gD
                                                              296yLi0fzgpIaOMZZsfez6emK3bin7xEU1oyrDGsiZ6M3JY+nr9aLhZIE2sBscHbgYB96ZNFKroU
                                                              f92zAccE47USpNKrAjB/2hgA9v8A9YrGXWz3LirO6GCfklwOBwB0BqL7M8agSoVZ/m3ZyMe3tTJI
                                                              ZGbAIDr1BPB/xqWRXKNuXK8cdzWHLrobRtEjhHyoHIV1Odw5B/8A1U2VpJI9y4KE9Scfj709JUUc
                                                              qE3c7fSmy7ZI2LP+742oB90+3fn3rFxfM77aGyd1oVfUAhj7cCpbYSNEysQrHjaOlQyKA4K5XA65
                                                              71NCrLHuZg4PTAwa0aTVirkDWmVZWwyk4YDgH0qSG1YMwABXgjB5pFkjZ2bac9xg4/z704XRi3Lg
                                                              IHGBnr/k09e5LaW4pzIiZGfLGBzyoJpl45KZTBxwPQU2FzudASQuC2Rz7Zp5k3KQRhuoI5x+Hf61
                                                              SbWotCrAgU9CWYjdj09frUj7SxC8gc5PAxTgSyZiwc8ZHYd+aTeEZ14IYck9DU66u5peysRhQ4Ib
                                                              DEEEsOBSM6BgYyCoHDDpT/3bxN8uQOoPQ/UVHDEuWAOGPTA6UyGk9GPExAJRNzEjO

4 个答案:

答案 0 :(得分:3)

您可以使用以下代码:

public static String encodeTobase64(Bitmap image) {
    Bitmap immagex=image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

    Log.e("LOOK", imageEncoded);
    return imageEncoded;
}

在onActivityResult()

中使用以下代码
 InputStream imageStream = null;
        try {
            imageStream = this.getContentResolver().openInputStream(selectedImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
        encodeTobase64(yourSelectedImage);

答案 1 :(得分:1)

这就是我在我的画廊意图的onActivityResult上的表现。

String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());

然后将整个事物转换为位图。

Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

这是来自ImageUtil Class的getRealPathFromURI方法。

public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result = null;
            String[] projection = {MediaStore.Images.Media.DATA};

            try {
                Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(projection[0]);
                result = cursor.getString(columnIndex);
                cursor.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
    }

这是我从位图到base64的转换。

public static String getBase64(Bitmap bitmap) {
if (bitmap != null) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);


   return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}

return null;
}

答案 2 :(得分:1)

试试这个......

public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

答案 3 :(得分:1)

这是一个类似的代码。我在我的应用程序中实现了相同的功能。您可以从图库或相机中选择图像,您可以将其转换为基础64.试试这个适用于我。希望它也适合你

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import in.invis.organickerala.utilities.CropOption;
import in.invis.organickerala.R;

public class Profile_Activity extends AppCompatActivity {

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;
    final String[] items = new String[]{"Take From Camera", "Select From Gallery"};

    ImageView picture;
    AlertDialog.Builder builder;
    ArrayAdapter<String> adapter;
    private AccountManager mAccountManager;
    private int PICK_IMAGE_REQUEST = 1;
    private SharedPreferences mPreferences, myPrefs;
    private SharedPreferences.Editor myPrefsEdit;
    private Uri mImageCaptureUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
        builder = new AlertDialog.Builder(this);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("Profile");
        }
       // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       // setSupportActionBar(toolbar);
       // getSupportActionBar().setDisplayHomeAsUpEnabled(true);



        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
        myPrefsEdit = myPrefs.edit();

        picture = (ImageView) findViewById(R.id.picture);
        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                builder.setTitle("Select Image");
                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) { //pick from camera
                        if (item == 0) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                            mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                    "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

                            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                            try {
                                intent.putExtra("return-data", true);

                                startActivityForResult(intent, PICK_FROM_CAMERA);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                            }
                        } else { //pick from file
                            Intent intent = new Intent();

                            intent.setType("Image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);

                            startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                        }
                    }
                });

                final AlertDialog dialog = builder.create();

                picture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.show();
                    }
                });

                //END CAMERA STUFF

            }// End OnCreate


        });







        String temp = myPrefs.getString("url", "defaultString");
        try {
            byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            picture.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.getMessage();
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_FROM_CAMERA:

                doCrop();

                break;

            case PICK_FROM_FILE:
                mImageCaptureUri = data.getData();

                doCrop();

                break;

            case CROP_FROM_CAMERA:
                Bundle extras = data.getExtras();

                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] b = baos.toByteArray();
                    String temp = Base64.encodeToString(b, Base64.DEFAULT);
                    myPrefsEdit.putString("url", temp);
                    myPrefsEdit.commit();

                    picture.setImageBitmap(photo);
                }

                File f = new File(mImageCaptureUri.getPath());

                if (f.exists()) f.delete();

                break;

        }
    }



    private void doCrop() {
        final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("Image/*");

        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);

        int size = list.size();

        if (size == 0) {
            Toast.makeText(this, "Can not find Image crop app", Toast.LENGTH_SHORT).show();

            return;
        } else {
            intent.setData(mImageCaptureUri);

            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);

            if (size != 0) {
                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);

                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                startActivityForResult(i, CROP_FROM_CAMERA);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle arrow click here
        if (item.getItemId() == android.R.id.home) {
            Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }



}