【问题标题】:Compress image file in android application在android应用程序中压缩图像文件
【发布时间】:2015-02-19 06:44:48
【问题描述】:

我正在尝试创建一个将图像从设备上传到远程服务器的应用程序一切正常,但我需要将文件的大小从几 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, 25, dos);”现在什么也没发生。申请没有掉,但是图片没有上传。在所有“conn”行之后,我在该行“dos = new DataOutputStream(conn.getOutputStream());”之后添加了行。也许我应该把它放在其他地方?

标签: php android image file image-compression


【解决方案1】:

我添加了这一行:

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

在这一行之后:

dos.writeBytes(lineEnd);

现在上传的图片尺寸更小了。

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 1970-01-01
    • 2017-03-28
    • 2011-09-21
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多