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

Java Android压缩图像并使用下面的代码将其上传到服务器,java,php,android,upload,Java,Php,Android,Upload,我有两个不同的Android代码,它们的工作方式几乎相同。第一个代码从gallery捕获图像并将其与标题一起上载到php服务器,而第二个代码从gallery捕获图像,并且当按下resize按钮时,图像将被压缩,大小和内存都会减小,但也会保持相同的图片质量。让我上传/粘贴这两个代码 但我的问题是 在压缩图像内存后,如何将第二个代码上载到服务器?或者,在上传到服务器之前,我将如何生成第一个代码,让它像代码二一样压缩它 第一个代码 Hello greetings and salutation. p

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

但我的问题是

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

第一个代码

Hello greetings and salutation. 
package net.simplifiedcoding.androiduploadimage;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.provider.MediaStore;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Base64;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.Toast;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.util.HashMap;
公共类MainActivity扩展AppCompatActivity实现View.OnClickListener{
私人按钮按钮;
私人按钮按钮;
私人编辑文本;
私人影像视图;
公共静态最终字符串键\u IMAGE=“IMAGE”;
公共静态最终字符串键\u TEXT=“name”;
公共静态最终字符串上载\u URL=”http://simplifiedcoding.16mb.com/PhotoUploadWithText/upload.php";
私有int PICK_IMAGE_REQUEST=1;
私有位图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonUpload=(Button)findViewById(R.id.buttonUpload);
ButtonCoose=(按钮)findViewById(R.id.ButtonCooseImage);
editText=(editText)findViewById(R.id.editText);
imageView=(imageView)findViewById(R.id.imageView);
ButtonCoose.setOnClickListener(此);
buttonUpload.setOnClickListener(这个);
}
私有void showFileChooser(){
意图=新意图();
intent.setType(“image/*”);
intent.setAction(intent.ACTION\u GET\u CONTENT);
startActivityForResult(Intent.createChooser(Intent,“选择图片”),PICK\u IMAGE\u请求);
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==PICK\u IMAGE\u REQUEST&&resultCode==RESULT\u OK&&data!=null&&data.getData()!=null){
Uri filePath=data.getData();
试一试{
位图=MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);
设置图像位图(位图);
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
公共字符串getStringImage(位图bmp){
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[]imageBytes=bas.toByteArray();
字符串encodedImage=Base64.encodeToString(imageBytes,Base64.DEFAULT);
返回图像;
}
public void uploadImage(){
最终字符串text=editText.getText().toString().trim();
最终字符串图像=getStringImage(位图);
类UploadImage扩展异步任务{
对话加载;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
加载=ProgressDialog.show(MainActivity.this,“请稍候…”,“上载”,false,false);
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
loading.dispose();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG.show();
}
@凌驾
受保护字符串doInBackground(无效…参数){
RequestHandler rh=新的RequestHandler();
HashMap param=新的HashMap();
参数put(键文本,文本);
参数put(按键图像,图像);
字符串结果=rh.sendPostRequest(上传URL,参数);
返回结果;
}
}
UploadImage u=新的UploadImage();
u、 执行();
}
@凌驾
公共void onClick(视图v){
如果(v==按钮选择){
showFileChooser();
}
如果(v==按钮加载){
上传图像();
}
}
}

第二个代码

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;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Color;
导入android.os.Bundle;
导入android.os.Environment;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.view;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.io.File;
导入java.io.IOException;
导入java.text.DecimalFormat;
导入java.util.Random;
导入id.zelory.compressor.compressor;
导入io.reactivex.android.schedulers.AndroidSchedulers;
导入io.reactivex.functions.Consumer;
导入io.reactivex.schedulers.schedulers;
公共类MainActivity扩展了AppCompatActivity{
私有静态最终整数选取图像请求=1;
私有图像视图;
私有ImageView压缩DimageView;
私有文本视图-实际文本视图;
私有文本视图压缩SizeTextView;
私有文件实现图像;
私有文件压缩图像;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
实现图像视图=(图像视图)findViewById(R.id.actual\u图像);
compressedImageView=(ImageView)findViewById(R.id.compressed_image);
现货
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];
}
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;
}