开发者

Uploading an image to a server in Android app

In my app I am capturing an image and uploading it to the server. The capturing and uploading part works fine in my Android device which is of 5 mega pixel.

But the app crashes occasionally when taking a photo. We've noticed if someone takes a picture that has a high megapixel setting, the photo does not upload and the app crashes.

How to reduce the size of a 8 megapixel photo to be able to upload without crashing? Do I have to compress the captured image. Following is my code to capture an image

ContentValues values = new ContentValues();  
values.put(MediaStore.Images.Media.TITLE,fileName);  
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);          
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
intent.putExtra(MediaStore.ACTION_IMAGE_CAPTURE, capturedImage);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);  
startActivityForResult(intent, 3);

I am uploading the image in OnActivity Result as follows

public void onActivityResult(int requestCode, int resultCode, final Intent data) 
{
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == 3) 
  {     
    String[] projection = { MediaStore.Images.Media.DATA};  
    Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
    int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst(); 
    capturedImage = cursor.getString(column_index_data);    
    String url = "http://xxxxxxxxxxxxxx.com/device_upload.php";
    new ProfileAddImageFileAsync().execute(url);
  }
}

And I am running a progress dialog box until the upload get completed, as follows

     class ProfileAddImageFileAsync extend开发者_高级运维s AsyncTask<String, String, String> 
      {                     
            @Override
            protected void onPreExecute() 
            {
                super.onPreExecute();
                showDialog(DIALOG_DOWNLOAD_PROGRESS);
            }        
            protected String doInBackground(String... Aurl) 
            {
                HttpURLConnection connection = null;
                DataOutputStream outputStream = null;
                DataInputStream inStream = null;
                try
                {
                    URL urlServer = new URL(aurl[0]);
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary =  "*****";
                    int bytesRead, bytesAvailable, bufferSize;
                    int maxBufferSize = 1*1024*1024;

                    FileInputStream fileInputStream = new FileInputStream(new File(capturedImage) );
                    connection = (HttpURLConnection) urlServer.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);

                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                    outputStream = new
                    DataOutputStream( connection.getOutputStream() );
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + capturedImage +"\"" + lineEnd);
                    outputStream.writeBytes(lineEnd);
                    bytesAvailable = fileInputStream.available();
                    Log.e("bytesAvailable ",""+bytesAvailable);

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    Log.e("bufferSize ",""+bufferSize);

                    byte[] buffer = new byte[bufferSize];
                    Log.e("bufer ",""+buffer);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

                    @SuppressWarnings("unused")
                    int serverResponseCode = connection.getResponseCode();

                    @SuppressWarnings("unused")
                    String serverResponseMessage = connection.getResponseMessage();       

                    fileInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
                catch (Exception ex)
                {
                    Log.e("SD Card image upload error: ","" + ex.getMessage());
                }
                try 
                {
                    inStream = new DataInputStream ( connection.getInputStream() );
                    String str;
                    while (( str = inStream.readLine()) != null)
                    {
                        IMAGE_RESPONSE = str;
                        ServerPost(str);
                    }
                    inStream.close();
                }
                catch (IOException ioex)
                {
                    Log.e("SD card doFile upload error: ","" + ioex.getMessage());      
                }
                return null;
            }
            protected void onProgressUpdate(String... Progress) 
            {
                 dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            }
            protected void onPostExecute(String unused) 
            {
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            }
    }

Please help me friends, the above code is my working code in my 5MP camera.


i got solution like this, i use to capture and compress the image.

Following is my camera part

 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
             file = new File(Environment.getExternalStorageDirectory(),  String.valueOf(System.currentTimeMillis()) + ".jpg"); 
             Log.e("ffffffffffiiiiiiiiilllllllllle ",""+file);
             f = String.valueOf(file);
             mCapturedImageURI = Uri.fromFile(file);
             Log.e("outputFileUri ",""+mCapturedImageURI);
             setupImage(intent);
             intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI); 
             startActivityForResult(intent, 3); 

i am uploading the image in OnActivity Result as follows

public void onActivityResult(int requestCode, int resultCode, final Intent data) 
{
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == 3) 
  {     
      capturedImage = f;
      String url = "http://xxxxxxxxxxxxxx.com/device_upload.php";
      new ProfileAddImageFileAsync().execute(url);
  }
}

And i am running an progress dialog box until the upload get completed, as follows

 class ProfileAddImageFileAsync extends AsyncTask<String, String, String> 
      {                     
            @Override
            protected void onPreExecute() 
            {
                super.onPreExecute();
                showDialog(DIALOG_DOWNLOAD_PROGRESS);
            }

            protected String doInBackground(String... aurl) 
            {
                HttpURLConnection connection = null;
                DataOutputStream outputStream = null;
                DataInputStream inStream = null;
                try
                {
                    URL urlServer = new URL(aurl[0]);
                    Log.e("URl image uploading ",""+urlServer);

                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary =  "*****";
                    int bytesRead, bytesAvailable, bufferSize;
                    int maxBufferSize = 1*1024*1024;
                    Log.e("maxBufferSize ",""+maxBufferSize);

                    FileInputStream fileInputStream = new FileInputStream(new File(capturedImage) );
                    connection = (HttpURLConnection) urlServer.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    Log.e("FileInput Stream in image upload ",""+fileInputStream);

                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                    outputStream = new
                    DataOutputStream( connection.getOutputStream() );
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + capturedImage +"\"" + lineEnd);
                    outputStream.writeBytes(lineEnd);
                    bytesAvailable = fileInputStream.available();
                    Log.e("bytesAvailable ",""+bytesAvailable);

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    Log.e("bufferSize ",""+bufferSize);

                    byte[] buffer = new byte[bufferSize];
                    Log.e("bufer ",""+buffer);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

                    @SuppressWarnings("unused")
                    int serverResponseCode = connection.getResponseCode();

                    @SuppressWarnings("unused")
                    String serverResponseMessage = connection.getResponseMessage();       

                    fileInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
                catch (Exception ex)
                {
                    Log.e("SD Card image upload error: ","" + ex.getMessage());
                }
                try 
                {
                    inStream = new DataInputStream ( connection.getInputStream() );
                    String str;
                    while (( str = inStream.readLine()) != null)
                    {
                        Log.e("ImageResponse ",""+str);
                        Appconstant.IMAGE_RESPONSE = str;
                        ProImgServerPost(str);
                        Log.e("ProImgServerPost ","added");
                        AddImgServerPost(str);
                        Log.e("AddImgServerPost ","added");
                    }
                    inStream.close();
                }
                catch (IOException ioex)
                {
                    Log.e("SD card doFile upload error: ","" + ioex.getMessage());      
                }
                return null;

            }

            protected void onProgressUpdate(String... progress) 
            {
                 Log.e("ANDRO_ASYNC",""+progress[0]);
                 dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
//               Bitmap bMap = BitmapFactory.decodeFile(capturedImage);
//               ProfileImgPreview.setImageBitmap(bMap);
            }

            protected void onPostExecute(String unused) 
            {
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                Bitmap bMap = BitmapFactory.decodeFile(capturedImage);
                ProfileImgPreview.setImageBitmap(bMap);
            }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜