Shakib Karami
Shakib Karami

Reputation: 678

Resize image before sending it to server by POST method

I'm sending a picked image from gallery to my PHP server in my app via POST method but sometimes the size of the image make this uploading so slow. this is my function for uploading the image :

public int uploadFile(final String selectedFilePath) {
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length - 1];

if (!selectedFile.isFile()) {
  runOnUiThread(new Runnable() {
    @Override
    public void run() {
      Log.i("ERROR", "Source File Doesn't Exist");
    }
  });
  return 0;
} else {
  try {
    FileInputStream fileInputStream = new FileInputStream(selectedFile);
    URL url = new URL(SERVER_URL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);//Allow Inputs
    connection.setDoOutput(true);//Allow Outputs
    connection.setUseCaches(false);//Don't use a cached Copy
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("ENCTYPE", "multipart/form-data");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    connection.setRequestProperty("uploaded_file", selectedFilePath);
    //creating new dataoutputstream
    dataOutputStream = new DataOutputStream(connection.getOutputStream());
    String[] tmp = selectedFilePath.split("/");
    tmp[tmp.length - 1] = userId + ".png";
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < tmp.length; i++) {
      if (i < tmp.length - 1) {
        result.append(tmp[i] + '/');
      } else {
        result.append(tmp[i]);
      }
    }
    String mynewstring = result.toString();
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
      + mynewstring + "\"" + lineEnd);
    dataOutputStream.writeBytes(lineEnd);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {
      dataOutputStream.write(buffer, 0, bufferSize);
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();
    if (serverResponseCode == 200) {
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          Log.i("IMAGE","Uploaded Successfully");
        }
      });
    }
    fileInputStream.close();
    dataOutputStream.flush();
    dataOutputStream.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(ProfileActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
      }
    });
  } catch (MalformedURLException e) {
    e.printStackTrace();
    Toast.makeText(ProfileActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
  } catch (IOException e) {
    e.printStackTrace();
    Toast.makeText(ProfileActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
    e.printStackTrace();
  }
  return serverResponseCode;
}

}

I searched but didn't find a way for resizing image before sending to the server by this "POST" method and I'm not using bitmap in this to resize that easily so anyone knows how can I fix this issue? any help will be much appreciated

Upvotes: 0

Views: 224

Answers (2)

Chamila Lakmal
Chamila Lakmal

Reputation: 81

File fileImage = createImageFileResize(); 
        try {
            ExifInterface ei = new ExifInterface(imageUri.getPath());
            int rotation  = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);

            OutputStream fOut = null;
            fOut = new FileOutputStream(fileImage);
            Bitmap pictureBitmap = BitmapFactory.decodeFile(imageUri.getPath());// obtaining the Bitmap
            pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
            fOut.flush(); 
            fOut.close(); 

            ExifInterface ei2 = new ExifInterface(fileImage.getPath());
            ei2.setAttribute(ExifInterface.TAG_ORIENTATION,String.valueOf(rotation));
            ei2.saveAttributes();

            File fdelete = new File(imageUri.getPath());
            if(fdelete.exists()){
                if (fdelete.delete()) {
                    System.out.println("file Deleted :" + imageUri.getPath());
                } else {
                    System.out.println("file not Deleted :" + imageUri.getPath());
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

created new file to store the resized image other than replacing the original. Exif functions are used to maintain the original rotation data. Hope this will helps to you

Upvotes: 1

Noman Uddin
Noman Uddin

Reputation: 307

You should use Glide library

implementation 'com.github.bumptech.glide:glide:4.8.0'

usage

Glide
.with(context)
.load(path)
.apply(new RequestOptions().override(600, 200))
.into(imageViewResizeCenterCrop);

Upvotes: 0

Related Questions