Image resize before upload (my upload / selection is ok)

Almost two weeks later ... I give up !!!

I want to load image from gallery and camera ...

startActivityForResult... ok!  
EXTERNAL_CONTENT_URI... ok!  
ACTION_IMAGE_CAPTURE... ok!  
onActivityResult... ok!  
Activity.RESULT_OK ('cause I'm on Fragment)... ok!  
getActivity().getContentResolver().query()... ok!  
BitmapFactory.Options, opts.inSampleSize, .decodeFile... ok!  

      

but i cant reduce the image size to 900px before uploading to server with ...

- FileInputStream(sourceFile);  
- HttpURLConnection  
- DataOutputStream( getOutputStream)  
- dos.writeBytes(form... name... file name...)
- dos.write(buffer, 0, bufferSize) 

      

I don't understand ...
- How to use "createScaledBitmap" in this case.
- How can I use "writeBytes (... filename =?)" If it doesn't have a path when creating a new bitmap (at least I think so).
- If I have the original image on disk, what is the "createScaledBitmap" result path?
- How does the buffer work (step by step will be great), and why is it not used in other examples on stackoverflow?

I have read many links including:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
But I've already used "options.inSampleSize" to generate a preview on my fragment and it seems to me what I need (in my case) "createScaledBitmap" to achieve my 900x900px image for upload.

If there is another way to upload resized images, include ... let me know!
(Any links would be helpful)

I know ... I have to use AsyncTask ... I'm working on it!;)

Please consider not speaking so technically, because I have the worst combination for learning Android: beginner and speak Spanish! xD

ADDED:
Can anyone help with what @GVSharma is saying here?
Loading a compressed image

"you have the string path first na.so to convert it to a bitmap and compress it. Instead of passing the file path as the first argument to this method, change that first argument to a Bitmap or you only need path to String, compressed bitmap to String. hope this can help you "(I don't know how to do this)

public int uploadFile(String sourceFileUri) {

    final 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()) {
         ...
    } else {
        try {      
            // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL(upLoadServerUri);

             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true);
             conn.setDoOutput(true);
             conn.setUseCaches(false);
             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);//This is just for info?

             dos = new DataOutputStream(conn.getOutputStream());
             dos.writeBytes(twoHyphens + boundary + lineEnd);
             dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""+fileName+"\"" + lineEnd);//How put in here a resized bitmap?
             dos.writeBytes(lineEnd);

             //Here I'm lost!
             bytesAvailable = fileInputStream.available();
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];

             bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

             //I think...
             //this is a way to transfer the file in little pieces to server, right?, wrong?
             //If anybody can explain this, step by step... THANKS!!!
             while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
              }
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage();
             Log.i("uploadFile", "Respuesta HTTP es: " + serverResponseMessage + ": " + serverResponseCode);

             if(serverResponseCode == 200){
                 ...               
             }
             fileInputStream.close();
             dos.flush();
             dos.close();
        } catch (MalformedURLException ex) {
            ...
        } catch (Exception e) { 
            ... 
        }

        dialog.dismiss();      
        return serverResponseCode;

    } // End else block
}//End uploadFile()

      

+3


source to share


1 answer


There are actually two ways to handle the above case, mentioned below:

1] Do some server side layout (in your webservice) so that you can pass the height and width when uploading the image to the server, this will reduce the size of the image no matter what height / width size you go through. This is the first solution.

2] As I understand it, if you can reduce the size of the bitmap by this code:



try
{
int inWidth = 0;
int inHeight = 0;

InputStream in = new FileInputStream(pathOfInputImage);

// decode image size (decode metadata only, not the whole image)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;

// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;

// decode full image pre-resized
in = new FileInputStream(pathOfInputImage);
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/dstWidth, inHeight/dstHeight);
// decode full image
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);

// resize bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

// save image
try
{
    FileOutputStream out = new FileOutputStream(pathOfOutputImage);
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
    Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
   Log.e("Image", e.getMessage(), e);
}

      

After following the above coding steps, you can use the image / bitmap load logic / code.

+3


source







All Articles