将摄像头捕获的图像上传到服

时间:2017-08-11 10:24:17

标签: java android

我是Android新手并学习android。我开发了一个应用程序,通过将图像保存在内部目录中,将摄像头捕获的图像上传到服务器。但是在尝试上传时应用程序停止了。我在这里附上我的代码。如果有人给我的解决方案会更有帮助。

这是我得到的错误:

08-11 16:25:48.638 9100-9438/in.inferon.click_cam E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: in.inferon.click_cam, PID: 9100
    java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
        at java.io.File.fixSlashes(File.java:185)
        at java.io.File.<init>(File.java:134)
        at java.io.FileInputStream.<init>(FileInputStream.java:103)
        at in.inferon.click_cam.MainActivity$DoFileUpload.doInBackground(MainActivity.java:187)
        at in.inferon.click_cam.MainActivity$DoFileUpload.doInBackground(MainActivity.java:170)
        at android.os.AsyncTask$2.call(AsyncTask.java:292)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
        at java.lang.Thread.run(Thread.java:818) 
08-11 16:25:48.848 9100-9139/in.inferon.click_cam D/OpenGLRenderer: endAllStagingAnimators on 0xb7c87ce8 (RippleDrawable) with handle 0xb7d2d030
08-11 16:25:49.088 9100-9100/in.inferon.click_cam E/WindowManager: android.view.WindowLeaked: Activity in.inferon.click_cam.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{14806d7c V.E..... R......D 0,0-684,232} that was originally added here
       at android.view.ViewRootImpl.<init>(ViewRootImpl.java:373)
       at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
       at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:90)
       at android.app.Dialog.show(Dialog.java:298)
       at in.inferon.click_cam.MainActivity$DoFileUpload.onPreExecute(MainActivity.java:179)
       at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
       at android.os.AsyncTask.execute(AsyncTask.java:539)
       at in.inferon.click_cam.MainActivity.createImageFile(MainActivity.java:155)
       at in.inferon.click_cam.MainActivity.onClick(MainActivity.java:79)
       at android.view.View.performClick(View.java:4788)
       at android.view.View$PerformClick.run(View.java:19923)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5401)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:919)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:714)
08-11 16:25:50.928 9100-9438/in.inferon.click_cam I/Process: Sending signal. PID: 9100 SIG: 9

这是我的主要课程:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_IMAGE_CAPTURE = 101;
    Button button_camera, button_save;
    private ImageView imageView;
    private ConnectionDetector cd;
    private Boolean upflag = false;
    public Bitmap imageBitmap, bitmapRotate;
    File file;
    String mCurrentPhotoPath;
    private ProgressDialog pDialog;
    String imageFileName;


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

        cd = new ConnectionDetector(MainActivity.this);


        button_camera = (Button) findViewById(R.id.button_camera);
        button_save = (Button) findViewById(R.id.button_save);
        imageView = (ImageView) findViewById(R.id.imageView);

        cd = new ConnectionDetector(getApplicationContext());

        button_camera.setOnClickListener(this);
        button_save.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.button_camera:

                Intent cameraintent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraintent, REQUEST_IMAGE_CAPTURE);


                break;

            case R.id.button_save:

                if (cd.isConnectingToInternet()) {

                    if (!upflag) {
                        Toast.makeText(MainActivity.this, "Image Not Captured..!", Toast.LENGTH_LONG).show();
                    } else {
                        try {
                            createImageFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(MainActivity.this, "No Internet Connection !", Toast.LENGTH_LONG).show();
                }

                break;

        }
    };

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

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
        {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);

            upflag = true;
        }
    }

    private void createImageFile() throws IOException {
        // Create an image file name
       // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        // imageFileName = "JPEG_" + timeStamp + "_";
        //File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        //File image = File.createTempFile(
          //      imageFileName,  /* prefix */
            //    ".jpg",         /* suffix */
              //  storageDir      /* directory */
        //);

        // Save a file: path for use with ACTION_VIEW intents
        //mCurrentPhotoPath = image.getAbsolutePath();


        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir

        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);

        imageFileName = "null" + n + ".jpg";

        File mypath=new File(directory,imageFileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            mCurrentPhotoPath= directory.getAbsolutePath();

            if (cd.isConnectingToInternet()) {
                try {
                    new DoFileUpload().execute();
                }catch (Exception e){
                    e.printStackTrace();
                }


            } else {
                Toast.makeText(MainActivity.this, "No Internet Connection..", Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();

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

        // return image;
    }

    public class DoFileUpload extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("wait uploading Image..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                // Set your file path here
                FileInputStream fstrm = new FileInputStream(mCurrentPhotoPath);
                // Set your server page url (and the file title/description)
                HttpFileUpload hfu = new HttpFileUpload("http://onefind.in/phpuploader/upload_image.php", "ftitle", "fdescription", imageFileName);
                upflag = hfu.Send_Now(fstrm);
            }

            catch (FileNotFoundException e) {
                // Error: File not found
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            if (upflag) {
                Toast.makeText(getApplicationContext(), "Uploading Complete", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Unfortunately file is not Uploaded..", Toast.LENGTH_LONG).show();
            }
        }
    }
}


public class HttpFileUpload implements Runnable {

    URL connectURL;
    String responseString;
    String Title;
    String fileName;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;
    HttpFileUpload(String urlString, String vTitle, String vDesc, String file){
        try{
            connectURL = new URL(urlString);
            Title= vTitle;
            Description = vDesc;
            fileName = file;
        }catch(Exception ex){
            Log.i("HttpFileUpload","URL Malformatted");
        }
    }

    Boolean Send_Now(FileInputStream fStream){
        fileInputStream = fStream;
        return Sending();
    }

    Boolean Sending(){

        System.out.println("file Name is :"+fileName);

        String iFileName = fileName;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="fSnd";
        try
        {
            Log.e(Tag,"Starting Http File Sending to URL");

            // Open a HTTP connection to the URL
            HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(Title);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(Description);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag,"Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[ ] buffer = new byte[bufferSize];

            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0,bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.close();

            dos.flush();

            Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

            InputStream is = conn.getInputStream();

            // retrieve the response from server
            int ch;

            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
            String s=b.toString();
            Log.i("Response",s);
            dos.close();

            if(String.valueOf(conn.getResponseCode()).equals("200"))
            {
                return true;
            }else{
                return false;
            }
        }
        catch (MalformedURLException ex)
        {
            Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
            Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
        return false;
    }

    @Override
    public void run() {
    }
}


public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
    }

    @SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        // alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}

1 个答案:

答案 0 :(得分:0)

在onClick方法中将代码更改为

case R.id.button_camera:
 Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        if (isCameraPermissionEnabled()) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    1);
        }
    }

同时添加此方法

public boolean isCameraPermissionEnabled() {

    return !(Build.VERSION.SDK_INT >= 23 &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED );
}

不要忘记在AndroidManifest.xml中添加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />