将4032x3024 / 12MP分辨率相机图像上传到服务器

时间:2017-07-25 17:09:46

标签: android

我最近发现为什么以前的问题我手机上的后置摄像头的照片没有通过我的Android应用程序上传。相机分辨率太高,为4032 x 3024,百万像素数为12MP,但我注意到当我降低这些品质时,它会起作用。看来我只能达到470万像素的高质量。 12MP的质量是否真的太大了?或者有没有办法在上传之前减小这个尺寸?

主要活动

package com.example.stins.orbotcamera;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.SyncStateContract;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private FloatingActionButton fab;
    private ImageView imageView;
    private Uri file;
    private GPSTracker gps;
    private EditText imageComment;
    private CoordinatorLayout coordinatorLayout;
    private TextView imageLat, imageLong;
    private String mLat, mLong;

    public static final String UPLOAD_URL = "http://192.168.1.77/UploadExamples/upload.php";

    private Bitmap bitmap;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageComment = (EditText) findViewById(R.id.imageComment);
        imageLat = (TextView) findViewById(R.id.imageLat);
        imageLong = (TextView) findViewById(R.id.imageLong);

        fab.setOnClickListener(this);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            fab.setEnabled(false);
            imageComment.setEnabled(false);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                fab.setEnabled(true);
                imageComment.setEnabled(true);
            }

            else{
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Accept all permissions to use app", Snackbar.LENGTH_INDEFINITE);
                snackbar.setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = getBaseContext().getPackageManager()
                                .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                });

                snackbar.setActionTextColor(Color.WHITE);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.GRAY);


                snackbar.show();
        }


        }

    }



    public void uploadImage() {
        //getting name for the image
        String name = imageComment.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(file);


        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .addParameter("latitude", mLat)
                    .addParameter("longitude", mLong)
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

            Log.d("Upload", "uploadImage: " + path);

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }



    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        String document_id = null;
        if (cursor != null) {
            document_id = cursor.getString(0);
        }
        if (document_id != null) {
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        }
        if (cursor != null) {
            cursor.close();
        }

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        String path = null;
        if (cursor != null) {
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }
        if (cursor != null) {
            cursor.close();
        }

        return path;
    }










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

        if (requestCode == 0 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            file = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), file);
                imageView.setImageBitmap(bitmap);
                imageComment.setVisibility(View.VISIBLE);

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



        if (requestCode == 0) {
            gps = new GPSTracker(MainActivity.this);

            if (resultCode == RESULT_OK) {
                if (gps.canGetLocation()) {
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                     mLat = Double.toString(latitude);
                     mLong = Double.toString(longitude);

                    imageLat.setText(mLat);
                    imageLong.setText(mLong);

                    // \n is for new line
                    //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                     final Snackbar snackbar = Snackbar
                            .make(coordinatorLayout, "Current location recorded", Snackbar.LENGTH_LONG);

                    snackbar.setActionTextColor(Color.WHITE);

                    View sbView = snackbar.getView();
                    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_on_white_24dp,0,0,0);
                    textView.setTextColor(Color.WHITE);


                    snackbar.show();
                } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.

                }

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout,"Picture Cancelled", Snackbar.LENGTH_SHORT);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_cancel_white_24dp,0,0,0);
                textView.setTextColor(Color.WHITE);

                snackbar.show();
            } else {
                // failed to capture image
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout,"Error Taking Picture", Snackbar.LENGTH_SHORT);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_error_outline_white_24dp,0,0,0);
                textView.setTextColor(Color.WHITE);

                snackbar.show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }





    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (item.getItemId()) {
            case R.id.action_send:
                if(imageView.getDrawable()==null){
                    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                    final Snackbar snackbar = Snackbar
                            .make(coordinatorLayout,"Sorry, you'll need an image for that!", Snackbar.LENGTH_SHORT);

                    View sbView = snackbar.getView();
                    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_error_outline_white_24dp,0,0,0);
                    textView.setTextColor(Color.WHITE);

                    snackbar.show();
                }
                else {
                    uploadImage();
                }
                return true;


        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {

        new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert)
                .setTitle("Exit")
                .setMessage("Are you sure you want to close Orbot Camera?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                })
                .setNegativeButton("No", null)
                .show();


    }

    @Override
    public void onClick(View v) {

        Intent i;
        if(v.getId()==R.id.fab)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);

        }

    }
}

0 个答案:

没有答案