简体   繁体   中英

Android resize image from gallery before upload via php

I've an application uploading an image choosen from gallery. Before upload I show the selected image in an ImageView and let the user choose another image or Upload current. I would downscale the image if widht or height are bigger than 1000 but I'm only able to scale the bitmap in the ImageView. Could anyone help me or give me any suggestion? Here is my code, any help would be much appreciated, thanks in advance.

    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;

    }

You can decode the image into a Bitmap using one of the static methods from the BitmapFactory class, whether that will be using the existing FileInputStream which you are opening or just passing in the file path.

Following that you can use the createScaledBitmap method to resize it down, and finally use compress to put it into your OutputStream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM