Skip to content Skip to sidebar Skip to footer

Taking A Picture Via Camera And Sending It To Server In Bytearray

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 as a b

Solution 1:

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.

privatestaticfinalintCAMERA_PHOTO=111;
private Uri imageToUploadUri;

privatevoidcaptureCameraImage() {
        IntentchooserIntent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
        Filef=newFile(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.

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    UriselectedImage= imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    BitmapreducedSizeBitmap= getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        ButtonuploadImageButton= (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) {

        Uriuri= Uri.fromFile(newFile(path));
        InputStreamin=null;
        try {
            finalintIMAGE_MAX_SIZE=1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Optionso=newBitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            intscale=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);

            Bitmapb=null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image// larger than target
                o = newBitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensionsintheight= b.getHeight();
                intwidth= b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                doubley= Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                doublex= (y / height) * width;

                BitmapscaledBitmap= 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);
            returnnull;
        }
    }

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) {
    Stringfinal_upload_filename="demo_image.png";
    Stringresponse=null;
    HttpURLConnectionconn=null;
    try {
        StringlineEnd="\r\n";
        StringtwoHyphens="--";
        Stringboundary="---------------------------14737809831466499882746641449";
        URLurl=newURL("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);
        DataOutputStreamdos=newDataOutputStream(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();
        InputStreamis= conn.getInputStream();
        ByteArrayOutputStreambaos=newByteArrayOutputStream();
        int bytesRead;
        byte[] bytes = newbyte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();
        response = newString(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!

Solution 2:

At first you need to create a file and save image on it and here's a code.

//method to save image in internal or external storage

privatevoidstoreImage(Bitmap image,String imageName) {
    FilepictureFile= getOutputMediaFile(imageName);
    if (pictureFile == null) {
        Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());return;
    } 
    try {
        FileOutputStreamfos=newFileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

//method to create file to save image on it

privateFilegetOutputMediaFile(String imageName){
    //create folder with name FoursquareAPIFile mediaStorageDir = newFile(Environment.getExternalStorageDirectory()
            + "/FoursquareAPI");

    // Create the storage directory if it does not existif (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            returnnull;
        }
    } 
    File mediaFile;
        String mImageName= imageName +".png";
        mediaFile = newFile(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
}

Post a Comment for "Taking A Picture Via Camera And Sending It To Server In Bytearray"