【发布时间】:2016-03-30 15:19:13
【问题描述】:
我将在我的 android 应用程序中创建附件。我需要附上图片。 这是我的代码:
...
attachButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select image"), CHOOSE_IMAGE);
}
});
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHOOSE_IMAGE) {
if(resultCode == RESULT_OK) {
Uri uri = data.getData();
ImageView imageView = new ImageView(this);
Bitmap bitmap = getDecodedImageFromUri(uri);
imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap getDecodedImageFromUri(Uri uri) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Rect rect = new Rect(0, 0, 0, 0);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, rect, options);
options.inSampleSize = getInSampleSize(options, 128, 128);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, rect, options); //HERE IS PROBLEM - bitmap = null.
return bitmap;
}
private int getInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if(height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
我添加评论哪里有问题。 所以,我做了调试,在这一刻:
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, rect, options);
位图等于null。
有什么问题?我做错了什么?
如您所见,这些帮助方法来自 android 开发者指南。
更新
我需要解码两次,因为我需要获取选项然后获取图像大小来计算 InSampleSize 以压缩此图像。
第二次,options 不等于 null - 我通过调试检查它。
但是,在第二个解码选项之后,outWidth 和 outHeight 为 -1。所以,它设置为默认值。我不知道这一刻会发生什么。
【问题讨论】:
标签: android android-intent bitmap bitmapfactory