Android压缩图像并使用以下代码将其上传到服务器

时间:2017-10-17 20:45:14

标签: java php android upload

Hello greetings and salutation. 

我有两种不同的 Android代码,它们的工作方式几乎相同。第一个代码从图库中捕获图像并将其标题上传到php服务器,而第二个代码从图库中捕获图像,当按下调整大小按钮时,图像被压缩,尺寸和内存都减少了,但也保持了相同的图片质量。让我上传/粘贴这两个代码。

但我的问题是

如何在压缩图像内存后将第二个代码上传到服务器?或者我如何在上传到服务器之前制作第一个代码让它像代码二那样压缩它?

第一个代码

package net.simplifiedcoding.androiduploadimage;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button buttonUpload;
private Button buttonChoose;

private EditText editText;
private ImageView imageView;

public static final String KEY_IMAGE = "image";
public static final String KEY_TEXT = "name";
public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/PhotoUploadWithText/upload.php";

private int PICK_IMAGE_REQUEST = 1;

private Bitmap bitmap;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonUpload = (Button) findViewById(R.id.buttonUpload);
    buttonChoose = (Button) findViewById(R.id.buttonChooseImage);

    editText = (EditText) findViewById(R.id.editText);
    imageView = (ImageView) findViewById(R.id.imageView);

    buttonChoose.setOnClickListener(this);
    buttonUpload.setOnClickListener(this);
}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}


public void uploadImage(){
    final String text = editText.getText().toString().trim();
    final String image = getStringImage(bitmap);
    class UploadImage extends AsyncTask<Void,Void,String>{
        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            HashMap<String,String> param = new HashMap<String,String>();
            param.put(KEY_TEXT,text);
            param.put(KEY_IMAGE,image);
            String result = rh.sendPostRequest(UPLOAD_URL, param);
            return result;
        }
    }
    UploadImage u = new UploadImage();
    u.execute();
}


@Override
public void onClick(View v) {
    if(v == buttonChoose){
        showFileChooser();
    }
    if(v == buttonUpload){
        uploadImage();
    }
}

}

第二个代码

package id.zelory.compressor.sample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;

import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;

private ImageView actualImageView;
private ImageView compressedImageView;
private TextView actualSizeTextView;
private TextView compressedSizeTextView;
private File actualImage;
private File compressedImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    actualImageView = (ImageView) findViewById(R.id.actual_image);
    compressedImageView = (ImageView) findViewById(R.id.compressed_image);
    actualSizeTextView = (TextView) findViewById(R.id.actual_size);
    compressedSizeTextView = (TextView) findViewById(R.id.compressed_size);

    actualImageView.setBackgroundColor(getRandomColor());
    clearImage();
}

public void chooseImage(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

public void compressImage(View view) {
    if (actualImage == null) {
        showError("Please choose an image!");
    } else {

        // Compress image in main thread
        //compressedImage = new Compressor(this).compressToFile(actualImage);
        //setCompressedImage();

        // Compress image to bitmap in main thread
        //compressedImageView.setImageBitmap(new Compressor(this).compressToBitmap(actualImage));

        // Compress image using RxJava in background thread
        new Compressor(this)
                .compressToFileAsFlowable(actualImage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) {
                        compressedImage = file;
                        setCompressedImage();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        showError(throwable.getMessage());
                    }
                });
    }
}

public void customCompressImage(View view) {
    if (actualImage == null) {
        showError("Please choose an image!");
    } else {
        // Compress image in main thread using custom Compressor
        try {
            compressedImage = new Compressor(this)
                    .setMaxWidth(640)
                    .setMaxHeight(480)
                    .setQuality(75)
                    .setCompressFormat(Bitmap.CompressFormat.WEBP)
                    .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES).getAbsolutePath())
                    .compressToFile(actualImage);

            setCompressedImage();
        } catch (IOException e) {
            e.printStackTrace();
            showError(e.getMessage());
        }

        // Compress image using RxJava in background thread with custom Compressor
        /*new Compressor(this)
                .setMaxWidth(640)
                .setMaxHeight(480)
                .setQuality(75)
                .setCompressFormat(Bitmap.CompressFormat.WEBP)
                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
                .compressToFileAsFlowable(actualImage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) {
                        compressedImage = file;
                        setCompressedImage();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        showError(throwable.getMessage());
                    }
                });*/
    }
}

private void setCompressedImage() {
    compressedImageView.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));
    compressedSizeTextView.setText(String.format("Size : %s", getReadableFileSize(compressedImage.length())));

    Toast.makeText(this, "Compressed image save in " + compressedImage.getPath(), Toast.LENGTH_LONG).show();
    Log.d("Compressor", "Compressed image save in " + compressedImage.getPath());
}

private void clearImage() {
    actualImageView.setBackgroundColor(getRandomColor());
    compressedImageView.setImageDrawable(null);
    compressedImageView.setBackgroundColor(getRandomColor());
    compressedSizeTextView.setText("Size : -");
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
        if (data == null) {
            showError("Failed to open picture!");
            return;
        }
        try {
            actualImage = FileUtil.from(this, data.getData());
            actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
            actualSizeTextView.setText(String.format("Size : %s", getReadableFileSize(actualImage.length())));
            clearImage();
        } catch (IOException e) {
            showError("Failed to read picture data!");
            e.printStackTrace();
        }
    }
}

public void showError(String errorMessage) {
    Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
}

private int getRandomColor() {
    Random rand = new Random();
    return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}

public String getReadableFileSize(long size) {
    if (size <= 0) {
        return "0";
    }
    final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

}

非常感谢你需要解决这个问题

1 个答案:

答案 0 :(得分:-1)

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

到这个

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

这将起作用