上传压缩图像

时间:2014-04-15 11:55:20

标签: android image

我是android新手。我创建了一个应用程序来将图像上传到服务器。它适用于小尺寸图像,但对于较大的图像(> 1 MB),这不起作用。 这是我上传图片的功能

class UploadFile extends AsyncTask<String,String,String>{
        private ProgressDialog pDialog;
        JSONObject jobj = null;
        String json,msg;
        String filepath,dat,remark,hid,pid,form;
        public UploadFile(String filepath,String remark,String dt,
                String hid,String pid, String form) {
            // TODO Auto-generated constructor stub
            this.filepath = filepath;
            this.dat = dt;
            this.remark =remark;
            this.hid=hid;
            this.pid=pid;
            this.form =form;
        }

        protected void onPreExecute() {

            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Uploading Image...Please wait");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

       }


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


            String fileName = filepath;

              HttpURLConnection conn = null;
              DataOutputStream dos = null;  
              String lineEnd = "\r\n";
              String twoHyphens = "--";
              String boundary = "*****";
              int bytesRead, bytesAvailable, bufferSize;
              byte[] buffer;
              int maxBufferSize = 1 * 1024 * 1024; 
              File sourceFile = new File(filepath); 

              if (!sourceFile.isFile()) {


                   Log.e("uploadFile", "Source File not exist :");


                   return null;

              }
              else
              {
                   try { 

                         // open a URL connection to the Servlet
                       FileInputStream fileInputStream = new FileInputStream(sourceFile);
                       URL url = new URL(upLoadServerUri);

                       // Open a HTTP  connection to  the URL
                       conn = (HttpURLConnection) url.openConnection(); 
                       conn.setDoInput(true); // Allow Inputs
                       conn.setDoOutput(true); // Allow Outputs
                       conn.setUseCaches(false); // Don't use a Cached Copy
                       conn.setRequestMethod("POST");
                       conn.setRequestProperty("Connection", "Keep-Alive");
                       conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);


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

                       dos.writeBytes(twoHyphens + boundary + lineEnd);
                       dos.writeBytes("Content-Disposition: form-data; name=\"hid\"" + lineEnd);
                       dos.writeBytes(lineEnd);
                       // You can assign values as like follows : 
                       dos.writeBytes(hid);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + lineEnd);

                       dos.writeBytes(twoHyphens + boundary + lineEnd);
                       dos.writeBytes("Content-Disposition: form-data; name=\"pid\"" + lineEnd);
                       dos.writeBytes(lineEnd);
                       // You can assign values as like follows : 
                       dos.writeBytes(pid);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + lineEnd);

                       dos.writeBytes(twoHyphens + boundary + lineEnd);
                       dos.writeBytes("Content-Disposition: form-data; name=\"form\"" + lineEnd);
                       dos.writeBytes(lineEnd);
                       // You can assign values as like follows : 
                       dos.writeBytes(form);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + lineEnd);

                       dos.writeBytes(twoHyphens + boundary + lineEnd);
                       dos.writeBytes("Content-Disposition: form-data; name=\"dt\"" + lineEnd);
                       dos.writeBytes(lineEnd);
                       // You can assign values as like follows : 
                       dos.writeBytes(dat);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + lineEnd);

                       dos.writeBytes(twoHyphens + boundary + lineEnd);
                       dos.writeBytes("Content-Disposition: form-data; name=\"remark\"" + lineEnd);
                       dos.writeBytes(lineEnd);
                       // You can assign values as like follows : 
                       dos.writeBytes(remark);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + lineEnd);


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



                       // create a buffer of  maximum size
                       bytesAvailable = fileInputStream.available(); 
                       bufferSize = Math.min(bytesAvailable, maxBufferSize);
                       buffer = new byte[bufferSize];

                       // read file and write it into form...
                       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);   

                        }

                       // send multipart form data necesssary after file data...
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                       // Responses from the server (code and message)

                       serverResponseCode = conn.getResponseCode();
                       String serverResponseMessage = conn.getResponseMessage();

                       Log.i("uploadFile", "HTTP Response is : "
                               + serverResponseMessage + ": " + serverResponseCode);
                       BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                       StringBuilder sb = new StringBuilder();
                       String line = null;

                       while((line = in.readLine()) != null){
                           sb.append(line + "\n");
                           Log.d(">>>>>>>>>", sb.toString());
                       }


                       in.close();
                       json = sb.toString();
                       Log.d("json" , json);

                       try{
                            jobj = new JSONObject(json);
                            msg = jobj.getString("message");
                            paths.add(jobj.getString("path"));
                            Log.d("msg>>>>>>>>>>>>",msg);

                        }catch(JSONException e){
                            Log.e("JSON Parser", "Error parsing data " + e.toString());
                        }

                       if(serverResponseCode == 200){


                       }    

                       //close the streams //
                       fileInputStream.close();
                       dos.flush();
                       dos.close();

                  } catch (MalformedURLException ex) {


                      ex.printStackTrace();



                      Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
                  } catch (Exception e) {

                      e.printStackTrace();


                      Log.e("Upload file to server Exception", "Exception : "
                                                       + e.getMessage(), e);  
                  }



               } // End else block 
              return msg; 
             } 
        protected void onPostExecute(String file_url) {

            successcount++;
             if(pDialog != null && pDialog.isShowing()){
                 pDialog.dismiss();
                 }
        }


    }

我的问题是如何压缩图像?以及在上述函数中传递此压缩图像的位置?

2 个答案:

答案 0 :(得分:2)

你需要做这个人:

1:获取图片并检查尺寸。例如:if fileSize&lt; = 1MB

2:ShrinkBitmap(因此大图像不会导致内存问题。请参阅下面的ShrinkBitmap()。

3:如果你想编码到base64,那么你可以做到并压缩到100%。请参阅下面的Encodetobase64()

4:发送到服务器

public Bitmap ShrinkBitmap(String file, int width, int height)
{
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);

    if(heightRatio > 1 || widthRatio > 1)
    {
        if(heightRatio > widthRatio)
        {
            bmpFactoryOptions.inSampleSize = heightRatio;
        }
        else
        {
            bmpFactoryOptions.inSampleSize = widthRatio;
        }
    }

    bmpFactoryOptions.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    return bitmap;
}  



    public String encodeTobase64(Bitmap image)
{
    String byteImage = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    try
    {
        System.gc();
        byteImage = Base64.encodeToString(b, Base64.DEFAULT);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    catch (OutOfMemoryError e)
    {
        baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        b = baos.toByteArray();
        byteImage = Base64.encodeToString(b, Base64.DEFAULT);
        Log.e("Bitmap", "Out of memory error catched");
    }
    return byteImage;
}  

此编码功能也在压缩位图。

古德勒克!!

答案 1 :(得分:0)

  1. 要压缩图像,请使用GitHub上的此库(缩小大小):

    https://github.com/zetbaitsu/Compressor

  2. 编码到base64:

  3. public String encodeBase64(Bitmap image){ ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOS); return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT); }
    1. 通过排球请求(Post或Get方法)将base64字符串发送到服务器:

      https://developer.android.com/training/volley/simple.html