在通过POST方法将图像发送到服务器之前调整图像大小

时间:2018-10-31 14:06:57

标签: android image post upload

我正在通过POST方法将图库中的图像发送到我的应用程序中的PHP服务器,但是有时图像的大小使上传速度如此之慢。这是我上传图片的功能:

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

}

我进行了搜索,但是在通过此“ POST”方法发送到服务器之前找不到用于调整图像大小的方法,并且我没有在其中使用位图轻松地调整大小,因此任何人都知道如何解决此问题? 任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

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

创建了新文件来存储调整大小的图像,而不是替换原始图像。 Exif函数用于维护原始旋转数据。希望对您有帮助

答案 1 :(得分:0)

您应该使用 Glide

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

用法

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