在Android上将图像从文件路径转换为base64不起作用

时间:2019-02-28 04:27:37

标签: android base64

所以我的问题是我需要将图像从文件路径转换为base64,但是当我转换返回的String时,这就是我所看到的: base64 String to image

我需要从真实图像中显示真实的base64字符串。

这是我的代码:

package com.example.myapplication;

    import android.Manifest;
    import android.app.Activity;
    import android.content.ContentValues;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v4.content.FileProvider;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Base64;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.w3c.dom.Text;

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import static android.os.Environment.getExternalStoragePublicDirectory;

    public class MainActivity extends AppCompatActivity {

        ImageView ivImage;
        String pathToFile;
        Integer REQUEST_CAMERA=1, SELECT_FILE=0;
        File image;
        TextView textView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);


            textView=(TextView)findViewById(R.id.textV);
            if(Build.VERSION.SDK_INT >= 23)
            {
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE} , 2);
            }

            FloatingActionButton fab = findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();*/

                    SelectImage();
                }
            });

        }

        private void SelectImage()
        {
            final CharSequence[] items = {"Camera", "Gallery", "Cancel"};

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Image");
            builder.setItems(items, new DialogInterface.OnClickListener(){
               @Override
                public void onClick(DialogInterface dialogInterface, int i )
               {
                   if(items[i].equals("Camera"))
                   {
                        dispatchPictureTakerAction();

                   }else if(items[i].equals("Gallery"))
                   {
                       Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                       intent.setType("image/*");
                       startActivityForResult(intent.createChooser(intent,"Select File"), SELECT_FILE);

                   }else if(items[i].equals("Cancel"))
                   {
                       dialogInterface.dismiss();
                   }
               }
            });
            builder.show();
        }
        private void dispatchPictureTakerAction()
        {
            Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if(takePic.resolveActivity(getPackageManager()) != null)
            {
               File photoFile = null;
               photoFile = createPhotoFile();

               if(photoFile != null)
               {
                   pathToFile = photoFile.getAbsolutePath();
                   Uri photoUri = FileProvider.getUriForFile(MainActivity.this,"com.thecodecity.cameraandroid.fileprovider", photoFile);
                   takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

                   startActivityForResult(takePic,1);
               }
            }

        }
        private File createPhotoFile()
        {
            String name = new SimpleDateFormat("yyyyMMdd_MMmmss").format(new Date());
            File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

            image = null;
            try
            {
                image = File.createTempFile(name, ".jpg", storageDir);


            }catch(Exception e)
            {
                Log.d("mylog", "Except : " + e.toString());
            }
            return image ;
        }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode,resultCode,data);

            if(resultCode == Activity.RESULT_OK)
            {
                if(requestCode == REQUEST_CAMERA)
                {
                    Bitmap bmp = BitmapFactory.decodeFile(pathToFile);
                    textView.setText(getFileToByte(pathToFile));




                }else if(requestCode == SELECT_FILE)
                {
                    Uri selectedImageUri = data.getData();


                }
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
        public static String getFileToByte(String filePath){
            Bitmap bmp = null;
            ByteArrayOutputStream bos = null;
            byte[] bt = null;
            String encodeString = null;
            try{
                bmp = BitmapFactory.decodeFile(filePath);
                bos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bt = bos.toByteArray();
                encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
            }catch (Exception e){
                e.printStackTrace();
            }
            return encodeString;
        }
        private String encodedImage(Bitmap bm)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
            byte[] b = baos.toByteArray();
            String encImage = Base64.encodeToString(b, Base64.DEFAULT);

            return encImage;
        }
    }

这是我转换为base64时的结果

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQ EBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ EBAQEBAQEBAQEBAQEBAQEBAQEBAQH/ WAARCBBADDADASIA AhEBAXEB/ 8QAGwAAAwEBAQEBAAAAAAAAAAAAAQIDBAAFCgn/ XABVEAACAAMEBgclAgEEAQIBAhcB AgMREGAhljETMKFRYfAjQnGBkaGxMO NTY8HR4fFSC4MEYpOjs3LDOXSC4/

2 个答案:

答案 0 :(得分:1)

您可以按照以下步骤获取base64:

     ByteArrayOutputStream bao = new ByteArrayOutputStream();
     bmp.compress(Bitmap.CompressFormat.JPEG, 100, bao);
     byte [] ba = bao.toByteArray();
     String yourBase64= Base64.encodeToString(ba,Base64.DEFAULT);

答案 1 :(得分:0)

使用位图,您可以像这样获得Base64:

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
 String encodeString = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);

或者您可以像这样从byte[]获得File

 public static byte[] readBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            throw new IOException("Could not completely read file " + file.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }