我从相机和画廊拍摄图像,获取图像后,我想在图像视图中显示图像。
摄像机成功捕获的图像显示在imageview中,但是当我想从图库中选择它时,它不会显示图像,也不会显示任何错误。它工作正常,但后来我在活动中添加了相机功能,但效果不佳。
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
} catch(FileNotFoundException ex) {
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v) {
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty()) {
subject.setError("subject is required");
} else if(det.isEmpty()) {
detail.setError("subject is required");
} else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
} else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
答案 0 :(得分:0)
这是我的代码,用于将画廊或相机中的舍入照片设置为ImageButton,并且它完美运行:
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImage();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
在您的代码中,尝试添加createScaledBitmap来调整照片大小,如下所示:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
答案 1 :(得分:0)
selectedImage = BitmapFactory.decodeStream(imageStream);
您应该检查selectedImage - 位图 - 是否为空。
我打赌selectedImage==null
。
如果位图对于可用内存而言太大,则会发生这种情况。
您应该在从流中加载时缩小它。
请记住:从相机中您只能获得缩略图。差别就是这样。
答案 2 :(得分:0)
只更改onActivityResult方法如果阻止表单id条件,则删除else,如下面的代码...
def date_to_numeric(df):
for col in dates:
print("Converting date variables to years: " + col, flush = True)
df[col] = df[col].apply(pd.to_datetime, format = '%b-%Y', errors = 'coerce')
df[col] = 2018 - df[col].apply(pd.to_datetime, errors = 'coerce').dt.year
return df