Php android应用中图像文件的压缩

Php android应用中图像文件的压缩,php,android,image,file,image-compression,Php,Android,Image,File,Image Compression,我正在尝试创建一个应用程序,将图像从设备上传到远程服务器。一切正常,但我需要将文件大小从几MB压缩到几十或数百KB。我做了一点研究,但我看到的每个地方都是关于压缩位图的,在我的代码中有一个文件和FileInputStream。这是我将图像发送到服务器的java代码: public class ImageUpload { private String filePath; private String picName; public ImageUpload(int num

我正在尝试创建一个应用程序,将图像从设备上传到远程服务器。一切正常,但我需要将文件大小从几MB压缩到几十或数百KB。我做了一点研究,但我看到的每个地方都是关于压缩位图的,在我的代码中有一个文件和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

   $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文件,它获取文件并将其保存在服务器上:

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

   $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);
在这一行之后:

BitmapFactory.decodeStream(fileInputStream).compress(Bitmap.CompressFormat.JPEG, 15, dos);
dos.writeBytes(lineEnd);
现在图像上载的大小变小了。

我添加了这一行:“BitmapFactory.decodeStream(fileInputStream).compress(Bitmap.CompressFormat.JPEG,25,dos);”现在什么也没发生。应用程序没有崩溃,但图片没有上传。我在这行“dos=newdataoutputstream(conn.getOutputStream());”之后添加了一行,在所有“conn”行之后。也许我应该把它放在别的地方?