【问题标题】:Uploading an image to a server in Android app在 Android 应用中将图像上传到服务器
【发布时间】:2011-09-08 06:42:59
【问题描述】:

在我的应用程序中,我正在捕获图像并将其上传到服务器。捕获和上传部分在我的 5 兆像素的 Android 设备上运行良好。

但应用在拍照时偶尔会崩溃。我们注意到如果有人拿 具有高百万像素设置的图片,照片无法上传并且应用程序崩溃。

如何减小 8 兆像素照片的大小以便能够在不崩溃的情况下上传? 我是否必须压缩捕获的图像。以下是我捕获图像的代码

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

我在 OnActivity Result 中上传图片如下

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);
  }
}

我正在运行一个进度对话框,直到上传完成,如下

     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]);
                    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);
            }
    }

请朋友们帮帮我,上面的代码是我在我的 5MP 相机中的工作代码。

【问题讨论】:

  • 应用崩溃时的错误是什么?你没有得到任何细节吗?
  • 抱歉,我无法获取这些详细信息...
  • 你可以看看 ACRA。它可以帮助你解决这个code.google.com/p/acra

标签: android camera


【解决方案1】:

我得到了这样的解决方案,我用它来捕获和压缩图像。

以下是我的相机部分

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

我正在上传 OnActivity Result 中的图像,如下所示

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);
  }
}

我正在运行一个进度对话框,直到上传完成,如下所示

 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);
            }
    }

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 2013-12-17
    • 2014-03-21
    • 2014-03-24
    • 1970-01-01
    • 2011-08-31
    • 2011-02-02
    • 2015-03-29
    • 2011-10-15
    相关资源
    最近更新 更多