我有这个代码来捕获图像或从库中选择然后裁剪它。图像未显示,而onActivityResult
内的数据变量为空。我该怎么做才能解决这个问题?请帮忙!!
提前致谢。
import java.io.File;
import java.io.FileOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
public class ProfileName extends Activity implements TextWatcher,
OnClickListener, ImageChooserListener {
int choice;
private static int RESULT_CAPTURE = 1;
private static int RESULT_LOAD_IMAGE = 2;
ImageView click;
ImageView cam;
boolean cond = false;
EditText nameText;
TextView name_view;
ImageView camImage;
String Name = null;
String fileName;
ImageView exist;
ImageView save;
Bitmap bm;
int currentState = 0;
ImageView btnForward, btnBack;
RelativeLayout rl_name, rl_profile_create, rl_display;
private ImageChooserManager imageChooserManager;
private int chooserType;
private String filePath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_name);
cam = (ImageView) findViewById(R.id.camera);
nameText = (EditText) findViewById(R.id.editText1);
nameText.addTextChangedListener(this);
btnForward = (ImageView) findViewById(R.id.btnForward);
btnForward.setOnClickListener(this);
btnBack = (ImageView) findViewById(R.id.btnBack);
btnBack.setOnClickListener(this);
save = (ImageView) findViewById(R.id.save);
save.setOnClickListener(this);
name_view = (TextView) findViewById(R.id.textView2);
camImage = (ImageView) findViewById(R.id.camImage);
exist = (ImageView) findViewById(R.id.existing_img);
exist.setOnClickListener(this);
click = (ImageView) findViewById(R.id.new_img);
click.setOnClickListener(this);
rl_name = (RelativeLayout) findViewById(R.id.rl_name);
rl_profile_create = (RelativeLayout) findViewById(R.id.rl_profile_create);
rl_display = (RelativeLayout) findViewById(R.id.rl_display);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Name = nameText.getText().toString();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnForward:
// if (Name != null) {
//
// Intent j = new Intent(ProfileName.this, CreateProfile.class);
// j.putExtra("name", nameText.getText().toString());
// j.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
// | Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(j);
// finish();
// } else {
// Toast.makeText(ProfileName.this, "Please Enter The Name",
// Toast.LENGTH_SHORT).show();
// }
if (currentState < 3) {
currentState++;
}
displayScreens();
break;
case R.id.btnBack:
if (currentState != 0) {
currentState--;
}
displayScreens();
break;
case R.id.save:
if (Name != null) {
save(bm);
Intent j = new Intent(ProfileName.this, MainActivity.class);
j.putExtra("bit", bm);
j.putExtra("name", Name);
j.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(j);
SharedPreferences settings = getSharedPreferences(
Start.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
finish();
} else {
Toast.makeText(ProfileName.this, "Please Enter The Name",
Toast.LENGTH_SHORT).show();
}
break;
case R.id.existing_img:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
choice = 2;
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.new_img:
// open();
chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_CAPTURE_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// TODO Auto-generated method stub
if (requestCode == RESULT_CAPTURE && resultCode == RESULT_OK
/* && null != data */&& choice == 1) {
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "img.jpg");
// Crop the captured image using an other intent
try {
/* the user's device may not support cropping */
cropCapturedImage(Uri.fromFile(file));
} catch (ActivityNotFoundException aNFE) {
// display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
// Bitmap bp = (Bitmap) data.getExtras().get("data");
// // save(bp);
// bm=bp;
// cam.setImageBitmap(bp);
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data && choice == 2) {
Uri selectedImage = data.getData();
try {
/* the user's device may not support cropping */
cropCapturedImage(selectedImage);
} catch (ActivityNotFoundException aNFE) {
// display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
String picturePath = cursor.getString(cursor
.getColumnIndex(filePathColumn[0]));
cursor.close();
// save(BitmapFactory.decodeFile(picturePath));
bm = BitmapFactory.decodeFile(picturePath);
// bm=ilu.decodeBitmapFromPath(picturePath);
cam.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
if (requestCode == 3 && data != null) {
// Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
// set image bitmap to image view
cam.setImageBitmap(thePic);
bm = thePic;
} else if (resultCode == RESULT_OK
&& (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
if (imageChooserManager == null) {
reinitializeImageChooser();
}
imageChooserManager.submit(requestCode, data);
}
}
private void reinitializeImageChooser() {
imageChooserManager = new ImageChooserManager(this, chooserType,
"myfolder", true);
imageChooserManager.setImageChooserListener(this);
imageChooserManager.reinitialize(filePath);
}
public void open() {
// Intent intent = new
// Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
// choice=1;
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
/* create instance of File with name img.jpg */
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "img1.jpg");
/* put uri as extra in intent object */
if (!file.exists()) {
file.mkdirs();
} else {
file.delete();
file.mkdirs();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/* start activity for result pass intent as argument and request code */
// startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
try {
startActivityForResult(intent, RESULT_CAPTURE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
choice = 1;
}
@SuppressLint("SdCardPath")
public void save(Bitmap bitM) {
// fileName=nameText.getText().toString()+".jpg";
fileName = Name;
File direct = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + "/FabFamily/Me");
if (!direct.exists()) {
direct = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + "/FabFamily/Me");
direct.mkdirs();
} else if (direct.exists()) {
direct.delete();
direct = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + "/FabFamily/Me");
direct.mkdirs();
}
File file = new File(new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + "/FabFamily/Me"), fileName + ".jpg");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitM.compress(Bitmap.CompressFormat.JPEG, 75, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayScreens() {
switch (currentState) {
case 0:
rl_name.setVisibility(View.VISIBLE);
rl_profile_create.setVisibility(View.GONE);
rl_display.setVisibility(View.GONE);
save.setVisibility(View.GONE);
btnBack.setVisibility(View.GONE);
btnBack.setVisibility(View.VISIBLE);
break;
case 1:
rl_name.setVisibility(View.GONE);
rl_profile_create.setVisibility(View.VISIBLE);
rl_display.setVisibility(View.GONE);
btnBack.setVisibility(View.VISIBLE);
btnForward.setVisibility(View.VISIBLE);
save.setVisibility(View.GONE);
break;
case 2:
rl_name.setVisibility(View.GONE);
rl_profile_create.setVisibility(View.GONE);
rl_display.setVisibility(View.VISIBLE);
btnForward.setVisibility(View.GONE);
btnBack.setVisibility(View.VISIBLE);
save.setVisibility(View.VISIBLE);
camImage.setImageBitmap(bm);
name_view.setText(Name);
break;
default:
break;
}
}
public void cropCapturedImage(Uri picUri) {
// call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 3);
}
@Override
public void onImageChosen(com.kbeanie.imagechooser.api.ChosenImage image) {
// TODO Auto-generated method stub
if (image != null) {
try {
// Bitmap photo = BitmapFactory.decodeFile(image
// .getFilePathOriginal());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
// Bitmap preview_bitmap=BitmapFactory.decodeFile(image,
Bitmap photo = BitmapFactory.decodeFile(
image.getFilePathOriginal(), options);
try {
ExifInterface exif = new ExifInterface(
image.getFilePathOriginal());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
// Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(),
photo.getHeight(), matrix, true); // rotating bitmap
// if (orientation != 0) {
// photo = getResizedBitmap(photo, 180, 360);
// }
} catch (Exception e) {
}
// if (photo.getWidth() > 180 && photo.getHeight() >
// 250) {
// photo = getResizedBitmap(photo, 180, 250);
// }
// imgVw.setImageBitmap(photo);
// txtImgPath.setText(image.getFilePathOriginal());
Log.i("sdfh", "IMAGEPATH :" + image.getFilePathOriginal());
//
// base64 = Utility.BitMapToString(photo);
// imgPathLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.i("", "dsvj on image chosen:" + e.getMessage());
}
}
}
@Override
public void onError(String reason) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
假设您正在询问数据&#39;从&RESFF_CAPTURE&#39;结果为空(在“onActivityResult&#39;”中有多个分支,这意味着无法捕获图像,即您没有任何内容。
相应地采取行动。如果你坚持&#39; null&#39; to&#39; setImageBitmap(null)&#39;,你什么都不变黑,或者你可以显示吐司,或者发现一些错误&#39;而是位图。或者退出,或者不退出,或者放弃,或者不放弃......
一般来说,你不应该问这样的问题,因为答案取决于你的意图。并在您的问题中放置420行代码并询问&#34;我该如何处理它?&#34;看起来像是要求我为我重新编写我的应用程序&#34;。