package com.example.myapplication;
import static com.loopj.android.http.AsyncHttpClient.LOG_TAG;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.ByteArrayOutputStream;
import cz.msebera.android.httpclient.Header;
@SuppressLint("NewApi")
public class cream00 extends AppCompatActivity implements View.OnClickListener {
private EditText editTextName0;
private EditText editTextName1;
private EditText editTextName2;
private EditText editTextName3;
private ProgressDialog prgDialog;
private int RESULT_LOAD_IMG = 1;
private int RESULT_TAKE_IMG = 2;
private RequestParams params = new RequestParams();
private String encodedString;
private Bitmap bitmap;
private String imgPath;
private static final int WRITE_PERMISSION = 0x01;
private static final int CREAM_PERMISSION = 0x01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cream00);
requestWritePermission();
prgDialog= new ProgressDialog(this);
prgDialog.setCancelable(false);
editTextName0 = (EditText) findViewById(R.id.editText0);
editTextName1 = (EditText) findViewById(R.id.editText1);
editTextName2 = (EditText) findViewById(R.id.editText2);
editTextName3 = (EditText) findViewById(R.id.editText3);
findViewById(R.id.choose_image).setonClickListener(this);
findViewById(R.id.upload_image).setonClickListener(this);
findViewById(R.id.take_image).setonClickListener(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == WRITE_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(LOG_TAG, "Write Permission Failed");
Toast.makeText(this, "You must allow permission write external storage to your mobile device.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void requestWritePermission(){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
}
if(checkSelfPermission(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},CREAM_PERMISSION);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.choose_image:
loadImage();
break;
case R.id.upload_image:
uploadImage();
break;
case R.id.take_image:
takeImage();
break;
}
}
public void takeImage() {
//这里就写了从相册中选择图片,相机拍照的就略过了
Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Log.d("camera", "takeImage: ok0");
startActivityForResult(takeIntent, RESULT_TAKE_IMG);
Log.d("camera", "takeImage: ok2");
}
public void loadImage() {
//这里就写了从相册中选择图片,相机拍照的就略过了
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
//当图片被选中的返回结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Log.d("camera", "takeImage: ok3");
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Log.d("camera", "takeImage: ok4");
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// 获取游标
Log.d("camera", "takeImage: ok5");
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.movetoFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imageView0);
imgView.setimageBitmap(BitmapFactory.decodeFile(imgPath));
} else if(requestCode == RESULT_TAKE_IMG && resultCode == RESULT_OK && null != data){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView imgView = (ImageView) findViewById(R.id.imageView0);
imgView.setimageBitmap(imageBitmap);
}else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
//开始上传图片
private void uploadImage() {
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("Converting Image to Binary Data");
prgDialog.show();
encodeImagetoString();
} else if((ImageView)findViewById(R.id.imageView0)!=null){
Log.d("camera", "takeImage: ok10086114514");
prgDialog.setMessage("Converting Image to Binary Data");
prgDialog.show();
encodeImagetoString0();
}else {
Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
}
public void encodeImagetoString0() {
new AsyncTask<Void, Void, String>(){
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
ImageView imgView = (ImageView) findViewById(R.id.imageView0);
bitmap = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// 压缩图片
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Base64图片转码为String
encodedString = Base64.encodetoString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
// 将转换后的图片添加到上传的参数中
params.put("image", encodedString);
params.put("leixing", editTextName0.getText().toString());
params.put("chexing", editTextName1.getText().toString());
params.put("yanse", editTextName2.getText().toString());
params.put("chepai", editTextName3.getText().toString());
// 上传图片
imageUpload();
}
}.execute(null, null, null);
}
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>(){
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// 压缩图片
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Base64图片转码为String
encodedString = Base64.encodetoString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
// 将转换后的图片添加到上传的参数中
params.put("image", encodedString);
params.put("filename", editTextName0.getText().toString());
// 上传图片
imageUpload();
}
}.execute(null, null, null);
}
public void imageUpload() {
prgDialog.setMessage("Invoking");
String url = "http://43.138.34.77:8080/androidtest/servlet/upload";
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), "upload success", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found", Toast.LENGTH_LONG).show();
}
// 当 Http 响应码'500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// 当 Http 响应码 404, 500
else {
Toast.makeText(
getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
"not connected to Internetn2. Web App is not deployed in App servern3." +
" App server is not runningn HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (prgDialog != null) {
prgDialog .dismiss();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。