在安卓应用程序中压缩图像文件


Compress image file in android application

我正在尝试创建一个将图像从设备上传到远程服务器的应用程序 一切正常,但我需要将文件大小从几 MB 压缩到几十或几百 KB。我做了一些研究,但到处都是关于压缩位图的,在我的代码中,我有一个File和FileInputStream。这是我将图像发送到服务器的java代码:

public class ImageUpload {
    private String filePath;
    private String picName;
    public ImageUpload(int num, String path) {
        filePath = path;
        picName = "Pic" + num + ".jpg";
        insertIntoServer();
    }
    public void insertIntoServer() {
        new Thread(new Runnable() {
            public void run() {
                uploadFile();
            }
        }).start();
    }
    public int uploadFile() {
        final String upLoadServerUri = "http://.../UploadToServer.php";
        HttpURLConnection conn;
        DataOutputStream dos;
        String lineEnd = "'r'n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(filePath);
        int serverResponseCode = 0;
        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File not exist : " + filePath);
            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", picName);
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name='"uploaded_file'";filename='"" + picName + "'"" + 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();
                if (serverResponseCode == 200) {
                    // Read response
                    final StringBuilder responseSB = new StringBuilder();
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null)
                        responseSB.append(line);
                    // Close streams
                    br.close();
                }
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
            }
            return serverResponseCode;
        }
    }
}

这是我的PHP文件,它获取文件并将它们保存在服务器上:

<?php
   $file_path = "../files/";
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

我需要在我的 php 文件或 java 文件中更改什么?提前谢谢你!

我添加了这一行:

BitmapFactory.decodeStream(fileInputStream).compress(Bitmap.CompressFormat.JPEG, 15, dos);

在此行之后:

dos.writeBytes(lineEnd);

现在图像以更小的尺寸上传。