我想从图库中获取图像将其转换为基本64字符串并将其发送到服务器

时间:2016-04-06 11:14:57

标签: android

下面是代码,但是当我想将这些信息插入到服务器中时,它给了我java.io.FileNotFoundException这个错误,那么怎样做可以让任何正文显示我的解决方案

public class AddItems extends Activity {
    ImageView iv;
    EditText et1, et2;
    Button b1;
    Bitmap bmp;
    String image1String, image2String, image3String;
    String imgPath, fileName;

    String encodedString;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_items);
        iv = (ImageView) findViewById(R.id.imageget);
        et1 = (EditText) findViewById(R.id.imageid);
        et2 = (EditText) findViewById(R.id.imagedes);
        b1 = (Button) findViewById(R.id.insert);

        b1.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        InputStream is;
                        BitmapFactory.Options bfo;
                        Bitmap bitmapOrg;
                        ByteArrayOutputStream bao ;

                        bfo = new BitmapFactory.Options();
                        bfo.inSampleSize = 2;
                        //bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);

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

                        HashMap<String, String> prams = new HashMap<String, String>();
                        prams.put("ImageID", et1.getText().toString());
                        prams.put("ImageDesc", et2.getText().toString());
                        prams.put("ImagePath", image1String);

                        Network network = new Network("insertimage.php", prams);


                        String RecivedString = null;
                        try {
                            RecivedString = network.ToRecieveDataFromWeb();
                            Jsonparsing jasonparsing = new Jsonparsing(RecivedString);
                            HashMap<String, String> hashMap = jasonparsing.ParseJsonObject(RecivedString);

                            if (hashMap.get("Success").toString().equals("1")) {
                                ShowOnUni("Good");


                            } else {

                                ShowOnUni(hashMap.get("Message") + "");
                            }

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

                    }
                }).start();
            }
        });

    enter code here

图像视图,用于保存图库或相机中的图像

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });



      GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void ShowOnUni(final String error1) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), error1 + "", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(AddItems.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 1);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            2);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
this is activity for result is this section the image from gallery is set into the imageview and is compressed 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        Uri selectedImageUri = null;
        String filePath = null;

        if (resultCode == RESULT_OK) {

            Bundle extra = data.getExtras();
            bmp = (Bitmap) extra.get("data");
            if (requestCode == 1) {

                iv.setImageBitmap(bmp);
                saveimage(bmp, requestCode);
                image1String = encodeimagetosting(bmp);

            }
            if (requestCode == 2 && resultCode == RESULT_OK) {


                selectedImageUri = data.getData();

            }
            if (selectedImageUri != null) {
                try {
                    // OI FILE Manager
                    String filemanagerstring = selectedImageUri.getPath();

                    // MEDIA GALLERY
                    String selectedImagePath = getPath(selectedImageUri);

                    if (selectedImagePath != null) {
                        filePath = selectedImagePath;
                    } else if (filemanagerstring != null) {
                        filePath = filemanagerstring;
                    } else {
                        Toast.makeText(getApplicationContext(), "Unknown path",
                                Toast.LENGTH_LONG).show();
                        Log.d("Bitmap", "Unknown path");
                    }

                    if (filePath != null) {
                        decodeFile(filePath);
                    } else {
                        bmp = null;
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Internal error",
                            Toast.LENGTH_LONG).show();
                    Log.d(e.getClass().getName(), e.getMessage(), e);
                }
            }
        }
    }

    enter code here

此方法用于保存从相机中捕获的内容

    private void saveimage(Bitmap bmp, int requestCode) {
        // TODO Auto-generated method stub


        File sdcard = new File("/sdcard/");
        File f = new File(sdcard, requestCode + ".jpeg");
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);

            bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
            out.flush();
            out.close();
            //   uris.add(Uri.fromFile(f));
            //Uri.parse(sdcard+"/"+requestCode+".png")


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String encodeimagetosting(Bitmap bitmap) {
        // TODO Auto-generated method stub


        Bitmap bm = bitmap;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);

        Log.d("Bitmap", imgString);
        return imgString;
    }

    private String encodeimagefromlibarary(Bitmap bitmap) {
        // TODO Auto-generated method stub


        Bitmap bm = bitmap;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        String imgStringlib = Base64.encodeToString(byteFormat, Base64.DEFAULT);

        Log.d("Bitmap", imgStringlib);
        return imgStringlib;
    }

    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bmp = BitmapFactory.decodeFile(filePath, o2);

        iv.setImageBitmap(bmp);

    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }
}

public class AddItems extends Activity {
    ImageView iv;
    EditText et1, et2;
    Button b1;
    Bitmap bmp;
    String image1String, image2String, image3String;
    String imgPath, fileName;

    String encodedString;

    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_items);
        iv = (ImageView) findViewById(R.id.imageget);
        et1 = (EditText) findViewById(R.id.imageid);
        et2 = (EditText) findViewById(R.id.imagedes);
        b1 = (Button) findViewById(R.id.insert);

        b1.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        InputStream is;
                        BitmapFactory.Options bfo;
                        Bitmap bitmapOrg;
                        ByteArrayOutputStream bao ;

                        bfo = new BitmapFactory.Options();
                        bfo.inSampleSize = 2;
                        //bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);

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

                        HashMap<String, String> prams = new HashMap<String, String>();
                        prams.put("ImageID", et1.getText().toString());
                        prams.put("ImageDesc", et2.getText().toString());
                        prams.put("ImagePath", image1String);

                        Network network = new Network("insertimage.php", prams);


                        String RecivedString = null;
                        try {
                            RecivedString = network.ToRecieveDataFromWeb();
                            Jsonparsing jasonparsing = new Jsonparsing(RecivedString);
                            HashMap<String, String> hashMap = jasonparsing.ParseJsonObject(RecivedString);

                            if (hashMap.get("Success").toString().equals("1")) {
                                ShowOnUni("Good");


                            } else {

                                ShowOnUni(hashMap.get("Message") + "");
                            }

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

                    }
                }).start();
            }
        });


        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void ShowOnUni(final String error1) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), error1 + "", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(AddItems.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 1);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            2);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        Uri selectedImageUri = null;
        String filePath = null;

        if (resultCode == RESULT_OK) {

            Bundle extra = data.getExtras();
            bmp = (Bitmap) extra.get("data");
            if (requestCode == 1) {

                iv.setImageBitmap(bmp);
                saveimage(bmp, requestCode);
                image1String = encodeimagetosting(bmp);

            }
            if (requestCode == 2 && resultCode == RESULT_OK) {


                selectedImageUri = data.getData();

            }
            if (selectedImageUri != null) {
                try {
                    // OI FILE Manager
                    String filemanagerstring = selectedImageUri.getPath();

                    // MEDIA GALLERY
                    String selectedImagePath = getPath(selectedImageUri);

                    if (selectedImagePath != null) {
                        filePath = selectedImagePath;
                    } else if (filemanagerstring != null) {
                        filePath = filemanagerstring;
                    } else {
                        Toast.makeText(getApplicationContext(), "Unknown path",
                                Toast.LENGTH_LONG).show();
                        Log.d("Bitmap", "Unknown path");
                    }

                    if (filePath != null) {
                        decodeFile(filePath);
                    } else {
                        bmp = null;
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Internal error",
                            Toast.LENGTH_LONG).show();
                    Log.d(e.getClass().getName(), e.getMessage(), e);
                }
            }
        }
    }

    private void saveimage(Bitmap bmp, int requestCode) {
        // TODO Auto-generated method stub


        File sdcard = new File("/sdcard/");
        File f = new File(sdcard, requestCode + ".jpeg");
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);

            bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
            out.flush();
            out.close();
            //   uris.add(Uri.fromFile(f));
            //Uri.parse(sdcard+"/"+requestCode+".png")


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String encodeimagetosting(Bitmap bitmap) {
        // TODO Auto-generated method stub


        Bitmap bm = bitmap;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);

        Log.d("Bitmap", imgString);
        return imgString;
    }

    private String encodeimagefromlibarary(Bitmap bitmap) {
        // TODO Auto-generated method stub


        Bitmap bm = bitmap;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        String imgStringlib = Base64.encodeToString(byteFormat, Base64.DEFAULT);

        Log.d("Bitmap", imgStringlib);
        return imgStringlib;
    }

    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bmp = BitmapFactory.decodeFile(filePath, o2);

        iv.setImageBitmap(bmp);

    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }
}

2 个答案:

答案 0 :(得分:0)

声明可变

  private final static int SELECT_PHOTO = 12345;
  String encodedImage;

全球变化和 通过以下代码打开您的Gallary

uploadbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HAS_IMAGAE = false;
            Intent i = new
                    Intent(Intent.ACTION_PICK, android.provider.MediaStore
                    .Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, SELECT_PHOTO);
        }
    });

通过以下代码接收您的图片

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

    switch (requestCode) {
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK) {
                try {
                    final Uri imageUri = data.getData();
                    imagepath = getPath(imageUri).toString();


                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

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

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imagepath = cursor.getString(columnIndex);
                    cursor.close();
                    //Toast.makeText(PersonalDetails.this,imagepath, Toast.LENGTH_SHORT).show();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

            encodedImage = BitMapToString(selectedImage);

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

            }
    }
}

将Bitmap转换为Base-64的Craete函数

  public String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();


    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

现在您可以通过Async Task和服务器端将此encodedImage传递给服务器,您必须将Base-64字符串转换为Image并保存。

答案 1 :(得分:0)

将此代码用于编码图像

{{1}}