我正在尝试从图库中读取图像,然后将该图像用于输入图像,下面是我的代码
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGetImageButton = (Button) findViewById(R.id.button_getImage);
mGetImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// SET action AND miniType
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
// REQUEST Uri of image
startActivityForResult(intent, REQUEST_IMAGE);
}
});
mImageViewForGallery = (ImageView) findViewById(R.id.imageView2);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {return;}
if (requestCode == REQUEST_IMAGE) {
Uri uri = data.getData();
// SET image
mImageViewForGallery.setImageURI(uri);
Drawable drawable = mImageViewForGallery.getDrawable();
InputStream is;
is = this.getResources().openRawResource(R.drawable.img1);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
}
}
在上面的代码is = this.getResources().openRawResource(R.drawable.img1);
正在从可绘制的文件夹名称img1中读取图像,但现在我的图像是我从图库中选择的图像,我如何将该图像作为输入流,就像我尝试的那样
InputStream is;
is=uri;
但它显示错误,对于来自c ++的java来说是新手。
编辑,在@Shawn回答后,我将此代码放在行onActivityResult
之后的Drawable drawable = mImageViewForGallery.getDrawable();
函数中:
InputStream is = this.getContentResolver().openInputStream(uri);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
InputStream Vign = this.getResources().openRawResource(R.drawable.p);
Bitmap bmInImg2 = BitmapFactory.decodeStream(Vign);
mPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
nPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
vPhotoIntArray = new int[bmInImg2.getWidth() * bmInImg2.getHeight()];
但它在this.getContentResolver().openInputStream(uri);
错误:
Unhandled exception type FileNotFoundException
在代码中使用InputStream Vign = this.getResources().openRawResource(R.drawable.p);
时出现错误。
答案 0 :(得分:1)
如果你有图像的Uri,你可以使用内容解析器解决它:
InputStream is = context.getContentResolver().openInputStream(uri);
别忘了关闭小溪。 (并检查null)。上下文有时候是你的活动或"这"。