1

I use this code to upload some image to my server. This code works fine, but on my server, i see that each image take a place arround 2Mb.

How can i reduce the image size on upload ?

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 

}

UPDATE

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);
wawanopoulos
  • 9,614
  • 31
  • 111
  • 166

3 Answers3

0

the upload-code will stay the same - but you will have to modify the images. There are basically 3 solutions:

  • reduce resolution
  • increase compression ( assuming that are jpegs - increasing compression will decrease the image quality )
  • reduce colors ( assuming we deal with png's this is a solution )

This really depends on your use-case.

ligi
  • 39,001
  • 44
  • 144
  • 244
  • Thanks. What is the best solution? And the easiest way ? No reducing color – wawanopoulos Jun 11 '14 at 14:05
  • I think you should go for reducing the resolution. Have a look at this: http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize – ligi Jun 11 '14 at 14:06
0

The code below will scale down the image by 8 times from it's original size. You can change it to suit your needs. Here, image is your image in bitmap.

        final BitmapFactory.Options options2 = new BitmapFactory.Options();
        options2.inSampleSize = 8;
        b = BitmapFactory.decodeFile(image, options2);
NiVeR
  • 9,644
  • 4
  • 30
  • 35
  • No, but maybe i have a problem. Question : After scale down the image (see my updated post), i call uploadFile method with "imagePath" parameter. Is it sure that imagePath refers to the image that have been scale down just before ? – wawanopoulos Jun 11 '14 at 14:43
  • You should store the path where the image is stored, and than upload that one. Another possibility is to upload directly when you scale down, if you can make your application behave in this way. – NiVeR Jun 11 '14 at 19:40
0

You can use below to compress bitmap

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

it will give same height and width.

Here you can change PNG to JPG to change resolution.

and 100 is quality of iamge.

see this solution if you allow to change dimension of image.

Community
  • 1
  • 1
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75