Taking a picture via camera and sending it to server in bytearray

后端 未结 2 1981
走了就别回头了
走了就别回头了 2020-12-20 09:32

I am working on an Andorid application in which I would like the user to take a picture and then to save it I am sending it over to the server. Now, I am sending the picture

2条回答
  •  悲哀的现实
    2020-12-20 10:17

    If you use Bundle extras = data.getExtras(); in your onActivityResult() then it will return thumbnail image not actual image.

    Here is code I have used for Capturing and Saving Camera Image then display it to ImageView. You can use according to your need.

    You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

    Here is method for opening capturing camera image activity.

    private static final int CAMERA_PHOTO = 111;
    private Uri imageToUploadUri;
    
    private void captureCameraImage() {
            Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
            chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            imageToUploadUri = Uri.fromFile(f);
            startActivityForResult(chooserIntent, CAMERA_PHOTO);
        }
    

    then your onActivityResult() method should be like this.

    @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
    
                if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                    if(imageToUploadUri != null){
                        Uri selectedImage = imageToUploadUri;
                        getContentResolver().notifyChange(selectedImage, null);
                        Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                        if(reducedSizeBitmap != null){
                            ImgPhoto.setImageBitmap(reducedSizeBitmap);
                            Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                              uploadImageButton.setVisibility(View.VISIBLE);                
                        }else{
                            Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                } 
            }
    

    Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

    private Bitmap getBitmap(String path) {
    
            Uri uri = Uri.fromFile(new File(path));
            InputStream in = null;
            try {
                final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
                in = getContentResolver().openInputStream(uri);
    
                // Decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(in, null, o);
                in.close();
    
    
                int scale = 1;
                while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                        IMAGE_MAX_SIZE) {
                    scale++;
                }
                Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
    
                Bitmap b = null;
                in = getContentResolver().openInputStream(uri);
                if (scale > 1) {
                    scale--;
                    // scale to max possible inSampleSize that still yields an image
                    // larger than target
                    o = new BitmapFactory.Options();
                    o.inSampleSize = scale;
                    b = BitmapFactory.decodeStream(in, null, o);
    
                    // resize to desired dimensions
                    int height = b.getHeight();
                    int width = b.getWidth();
                    Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
    
                    double y = Math.sqrt(IMAGE_MAX_SIZE
                            / (((double) width) / height));
                    double x = (y / height) * width;
    
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                            (int) y, true);
                    b.recycle();
                    b = scaledBitmap;
    
                    System.gc();
                } else {
                    b = BitmapFactory.decodeStream(in);
                }
                in.close();
    
                Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                        b.getHeight());
                return b;
            } catch (IOException e) {
                Log.e("", e.getMessage(), e);
                return null;
            }
        }
    

    EDIT:

    Here is method for uploading image to server.

    /**
     * Upload Image to server
     *
     * @param file              image to be saved
     * @param compressorQuality quality of image
     * @return path of uploaded image in server
     */
    private String uploadImage(Bitmap file, int compressorQuality) {
        String final_upload_filename = "demo_image.png";
        String response = null;
        HttpURLConnection conn = null;
        try {
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "---------------------------14737809831466499882746641449";
            URL url = new URL("image_upload_url");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", final_upload_filename);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
            dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
            dos.writeBytes(lineEnd);
            file.compress(CompressFormat.PNG, compressorQuality, dos);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            dos.flush();
            dos.close();
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int bytesRead;
            byte[] bytes = new byte[1024];
            while ((bytesRead = is.read(bytes)) != -1) {
                baos.write(bytes, 0, bytesRead);
            }
            byte[] bytesReceived = baos.toByteArray();
            baos.close();
            is.close();
            response = new String(bytesReceived);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return response;
    }
    

    You need to make upload script in backend server to store image data in particular folder.

    I hope it helps!

提交回复
热议问题