上传压缩图片

2024-03-31

我是安卓新手。我创建了一个应用程序来将图像上传到服务器。它非常适合小尺寸图像,但对于较大图像(> 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();
                 }
        }


    }

我的问题是如何压缩图像?以及在上面的函数中将压缩图像传递到哪里?


你需要做这个人:

1:获取图像并检查尺寸。例如:如果文件大小

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

该编码功能也压缩位图。

祝你好运!!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

上传压缩图片 的相关文章

随机推荐