在我的应用中,用户可以从图库或相机中添加图像,并显示在
中ImageView的。我想要做的是将图像发送到我的服务器。为此,
我应该将其转换为Base64
类型。
一切都很顺利,但我不知道如何获取imageView的内容进行转换,
以及准确放置代码的位置。
我的活动是:
public class MainActivity extends Activity {
private static int FROM_CAMERA = 1;
private static int FROM_GALLERY = 2;
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputEmail;
Button sendData;
JSONObject json;
ImageView userImg;
private static String url_create_user = "http://localhost/android_connect/create_user.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputName = (EditText)findViewById(R.id.userName);
inputEmail = (EditText)findViewById(R.id.email);
sendData = (Button)findViewById(R.id.send);
userImg = (ImageView)findViewById(R.id.userImage);
sendData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isNetworkConnected())
new CreateNewUser().execute();
else
Toast.makeText(getApplicationContext(), "Please connect to internet!", Toast.LENGTH_LONG).show();
}
});
userImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] options = new String[]{"Camera","Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(options, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent c = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(c, FROM_CAMERA);
}
else{
Intent g = new Intent(Intent.ACTION_GET_CONTENT);
g.setType("image/*");
startActivityForResult(g, FROM_GALLERY);
}
}
});
builder.create();
builder.show();
}
});
}
class CreateNewUser extends AsyncTask<String, String,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating user...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
String username = inputName.getText().toString();
String email = inputEmail.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
json = jsonParser.makeHttpRequest(url_create_user, "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if(json != null){
Toast.makeText(getApplicationContext(), "The data has been sent successfully!", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Failed to send data!", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imageView = (ImageView)findViewById(R.id.userImage);
if (requestCode == FROM_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else{
if(requestCode == FROM_CAMERA && resultCode == RESULT_OK && null != data )
{
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
imageView.setImageBitmap(photo);
}
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) return false;
else return true;
}
}
这是将图片转换为base64
的代码:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
我应该在 doInBackground 方法中添加这句话:
params.add(new BasicNameValuePair("image", image_str));
感谢!!!
答案 0 :(得分:1)
这是获取Imageview位图的方法:
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
转换为base64后。
答案 1 :(得分:1)
我解决了我的问题。这是解决方案:
要将图像的内容添加到位图,请执行此操作 -
Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();
这很好用,没有任何错误。
我将转换代码放在 onActivityResult()中,如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FROM_GALLERY && resultCode == RESULT_OK && null != data) {
//Getting the image from gallery and set it to imageView
}
else{
if(requestCode == FROM_CAMERA && resultCode == RESULT_OK && null != data )
{
//Getting the image from camera and set it to imageView
}
}
Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte [] byte_arr = stream.toByteArray();
image = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
一切顺利。