簡體   English   中英

Android通過php上載圖片庫之前調整圖片大小

[英]Android resize image from gallery before upload via php

我有一個應用程序上傳從圖庫中選擇的圖像。 上傳之前,我會在ImageView中顯示所選圖像,然后讓用戶選擇其他圖像或“上傳當前圖像”。 如果寬度或高度大於1000,我會縮小圖像,但只能縮放ImageView中的位圖。 有人可以幫助我還是給我任何建議? 這是我的代碼,在此先感謝您的幫助。

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath();
        //Uri imagename=data.getData();
        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if(width>=1000 || height >= 1000){
            width = width/3;
            height = height/3;
            bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
            }
        imageview.setImageBitmap(bitmap);
        uploadButton.setVisibility(View.VISIBLE);

    }
}
public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public int uploadFile(String sourceFileUri) {

    int day, month, year;
    int second, minute, hour;
    GregorianCalendar date = new GregorianCalendar();

    day = date.get(Calendar.DAY_OF_MONTH);
    month = date.get(Calendar.MONTH);
    year = date.get(Calendar.YEAR);

    second = date.get(Calendar.SECOND);
    minute = date.get(Calendar.MINUTE);
    hour = date.get(Calendar.HOUR);

    String name=(hour+""+minute+""+second+""+day+""+(month+1)+""+year);
    String tag=name+".jpg";
    String fileName = sourceFileUri.replace(sourceFileUri,tag);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :"+imagepath);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"+ imagepath);
            }
        });

        return 0;

    }
    else
    {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false); 
            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", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

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

            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(UploadImage.this, getString(R.string.uploadone), Toast.LENGTH_SHORT).show();
                    }
                });
                Intent intent = new Intent(UploadImage.this, ProfileActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadImage.this, getString(R.string.errorupload), Toast.LENGTH_LONG).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadImage.this, getString(R.string.errorupload), Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server", "Exception : "  + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    }

您可以使用BitmapFactory類中的一種靜態方法將圖像解碼為Bitmap ,無論是使用現有的FileInputStream (您正在打開的文件)還是只是傳入文件路徑。

接下來,您可以使用createScaledBitmap方法調整其大小,最后使用compress將其放入您的OutputStream

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM