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

Android:上传到服务器时减小图像大小,android,httpurlconnection,fileinputstream,Android,Httpurlconnection,Fileinputstream,我使用此代码将一些图像上传到我的服务器。 这段代码运行得很好,但在我的服务器上,我看到每个图像都占据2Mb左右的位置 如何减少上传时的图像大小 public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHy

我使用此代码将一些图像上传到我的服务器。 这段代码运行得很好,但在我的服务器上,我看到每个图像都占据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种解决方案:

降低分辨率 增加压缩(假设是JPEG)-增加压缩将降低图像质量 减少颜色假设我们处理png的这是一个解决方案
这实际上取决于您的用例。

下面的代码将图像从原始大小缩小8倍。你可以改变它来满足你的需要。这里,图像是位图中的图像

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

您可以使用下面的命令来压缩位图

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的质量


如果允许更改图像的尺寸,请查看此图。

谢谢。最好的解决方案是什么?最简单的方法是什么?不,我想你应该降低分辨率。看看这个:没有,但也许我有个问题。问题:在缩小图像比例后,请参阅我更新的帖子,我使用imagePath参数调用uploadFile方法。是否确定imagePath指的是刚刚缩小的图像?您应该存储存储图像的路径,然后上载该路径。另一种可能性是,如果可以使应用程序以这种方式运行,则可以在缩小比例时直接上载。