我正在尝试从图库中打开图像并在其上放置一个随机矩形。但是当我单击按钮打开图库时,会发生以下异常。
java.lang.IllegalArgumentException:width和height必须是> 0
public class MainActivity extends Activity implements OnClickListener {
TextView textView;
ImageView image1;
Button get_image, save_image, read_image;
String selectedImagePath;
int SELECT_PICTURE = 1;
String DB_NAME = "test.db";
String TABLE_NAME = "mytable";
String pts_table="ptstable";
Bitmap bmp;
Intent intent;
Canvas cnvs;
Uri selectedImageUri;
Random r;
int x,y;
Paint paint;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r=new Random();
image1 = (ImageView) findViewById(R.id.imageView1);
//image2 = (ImageView) findViewById(R.id.imageView2);
textView = (TextView) findViewById(R.id.textView1);
get_image = (Button) findViewById(R.id.get_image);
get_image.setOnClickListener(this);
save_image = (Button) findViewById(R.id.save_image);
save_image.setOnClickListener(this);
read_image = (Button) findViewById(R.id.read_image);
read_image.setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.get_image:
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE && data!=null) {
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
bmp=Bitmap.createBitmap(image1.getHeight(),image1.getWidth(),Bitmap.Config.RGB_565);
cnvs=new Canvas(bmp);
paint=new Paint();
paint.setColor(Color.RED);
cnvs.drawBitmap(BitmapFactory.decodeFile(selectedImagePath), 0,0,null);
cnvs.drawRect(50, 50, 100, 100, paint);
image1.setImageBitmap(bmp);
//image1.setImageURI(selectedImageUri);
}
}
}
@SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
这发生在
的onActivityResult()内部bmp=Bitmap.createBitmap(img.getHeight(),img.getWidth(),Bitmap.Config.RGB_565);
有人可以帮帮我吗?提前致谢
答案 0 :(得分:0)
我认为您只需添加一些防御代码来检查返回数据是否可用于您的下一个操作但不立即使用它。
不知何故,由于各种Android设备的不同,返回数据并不总是在您的脑海中。
答案 1 :(得分:0)
使用此:
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
img.setImageBitmap(bm);
uploadImagePath = tempPath;
希望这会对你有所帮助..