Android:上传到服务器时减小图像大小

时间:2014-06-11 13:50:00

标签: android httpurlconnection fileinputstream

我使用此代码将一些图像上传到我的服务器。 这段代码工作正常,但在我的服务器上,我看到每张图片都占据了2Mb的位置。

如何在上传时缩小图片尺寸?

public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
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(sourceFileUri); 

if (!sourceFile.isFile()) {
    dialog.dismiss(); 
    Log.e("uploadFile", "Erreur durant le traitement de la photo :" +imagePath);
    return 0;
}
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);
        conn.setRequestProperty("uploaded_file", fileName); 

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

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

        if(serverResponseCode == 200){
            // OK ..                
        }    

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

    } catch (MalformedURLException ex) {
        dialog.dismiss();  
        ex.printStackTrace();
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(New_annonce_act_step3.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
            }
        });
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        dialog.dismiss();  
        e.printStackTrace();
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(New_annonce_act_step3.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
            }
        });
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
    }
    dialog.dismiss();       
    return serverResponseCode; 
} // End else block 

}

更新

FileInputStream in = new FileInputStream(destination);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 15;
                imagePath = destination.getAbsolutePath();
                Log.d("INFO", "PATH === " +imagePath);
                Bitmap bmp = BitmapFactory.decodeStream(in, null, options);

3 个答案:

答案 0 :(得分:0)

上传代码将保持不变 - 但您必须修改图像。基本上有3种解决方案:

  • 降低分辨率
  • 增加压缩(假设是jpeg - 增加压缩会降低图像质量)
  • 减少颜色(假设我们处理png这是一个解决方案)

这实际上取决于您的用例。

答案 1 :(得分:0)

下面的代码会将图像从原始尺寸缩小8倍。您可以根据自己的需要进行更改。在这里,image是位图中的图像。

        final BitmapFactory.Options options2 = new BitmapFactory.Options();
        options2.inSampleSize = 8;
        b = BitmapFactory.decodeFile(image, options2);

答案 2 :(得分:0)

您可以使用以下方法压缩位图

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

它会给出相同的高度和宽度。

您可以在此处将PNG更改为JPG以更改分辨率。

和100是iamge的质量。

如果您允许更改图片尺寸,请参阅此solution