[英]Android - How to put an imageview that loads image from sdcard or camera roll?
I'm writing an app that I need to put an image view of which user has to load an image by click on it. 我正在写一个应用程序,我需要放置一个图像视图,用户必须单击该图像视图才能加载图像。 After clicking I'm to give options for user to select whether he intents to load a stored image from the phone itself or take a new shot from it's camera.
单击后,我将为用户提供选项,供用户选择是打算从手机本身加载存储的图像还是从相机拍摄新照片。
This question might be redundant but almost none of the similar questions/issues revealed in here didn't reach what I'm trying to do. 这个问题可能是多余的,但是在这里揭示的类似问题/问题几乎都没有达到我想做的事情。
Ps I'm working on Android API15 with Eclipse 4.2 (JUNO) SDK installed. 附言:我正在使用安装了Eclipse 4.2(JUNO)SDK的Android API15。
Here is the snippet code of main activity which gives me an error: 这是主要活动的代码片段,给我一个错误:
package test.imgbyte.conerter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.net.Uri;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
public class FindImgPathActivity extends Activity
{
private Uri mImageCaptureUri;
static final int CAMERA_PIC_REQUEST = 1337;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imgfilepath);
Button camera = (Button) findViewById(R.id.btnLoad);
camera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imgLoaded);
image.setImageBitmap(thumbnail);
String pathToImage = mImageCaptureUri.getPath();
// pathToImage is a path you need.
// If image file is not in there,
// you can save it yourself manually with this code:
File file = new File(pathToImage);
FileOutputStream fOut;
try
{
fOut = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // You can choose any format you want
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
Error I get is like this from LogCat: 我从LogCat得到的错误是这样的:
11-05 19:23:11.777: E/AndroidRuntime(1206): FATAL EXCEPTION: main
11-05 19:23:11.777: E/AndroidRuntime(1206): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1337, result=-1, data=Intent { act=inline-data (has extras) }} to activity {test.imgbyte.conerter/test.imgbyte.conerter.FindImgPathActivity}: java.lang.NullPointerException
Ah. 啊。 This error.
这个错误。 I'd spent ages deciphering what it meant, apparently the result has some null field that you're trying to access.
我花了很长时间来解释它的含义,显然结果中包含您要访问的某些空字段。 In your case it's the mImageCaptureUri field that you've not really initialized with a file.
在您的情况下,您尚未真正使用文件初始化的是mImageCaptureUri字段。 The way to start a camera intent is to create a file, and pass it's Uri to the intent as the EXTRA_OUTPUT.
启动相机意图的方法是创建一个文件,并将其Uri作为EXTRA_OUTPUT传递给该意图。
File tempFile = new File("blah.jpg");
...
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
...
You can then use the file.getAbsolutePath() method to load the Bitmap. 然后,您可以使用file.getAbsolutePath()方法加载位图。
Given we are on this point let me share with you a very important point I learnt last week about loading Bitmaps directly... Don't do it! 考虑到这一点,让我与您分享我上周学到的有关直接加载位图的非常重要的一点……不要这样做! It took me a week to understand why, and when I did I couldn't believe I didn't understand earlier, it's all a play on memory.
我花了一个星期的时间来了解原因,当我这样做的时候,我简直不敢相信自己不了解,这全都是为了记忆。
Use this code to load Bitmaps efficiently. 使用此代码可以有效地加载位图。 (Once you have the file, just use file.getAbsolutePath() in BitmapFactory.decodeFile()):
(一旦有了文件,只需在BitmapFactory.decodeFile()中使用file.getAbsolutePath()即可):
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
Just pass your file.getAbsolutePath() as the first argument, along with the required width and height to the decodeSampledBitmapFromPath function to get an efficiently loaded Bitmap. 只需将您的file.getAbsolutePath()作为第一个参数传递,并将所需的宽度和高度传递给decodeSampledBitmapFromPath函数即可获得有效加载的位图。 This code was modified from it's version here on the Android docs.
此代码是从Android文档此处的版本修改而来的。
Edit: 编辑:
private Uri mImageCaptureUri; // This needs to be initialized.
static final int CAMERA_PIC_REQUEST = 1337;
private String filePath;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imgfilepath);
// Just a temporary solution, you're supposed to load whichever directory you need here
File mediaFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Temp1.jpg");
filePath = mediaFile.getABsolutePath();
Button camera = (Button) findViewById(R.id.btnLoad);
camera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST)
{
if(resultCode == RESULT_OK)
{
int THUMBNAIL_SIZE = 64;
// Rest assured, if the result is OK, you're file is at that location
Bitmap thumbnail = decodeSampledBitmapFromPath(filePath, THUMBNAIL_SIZE, THUMBNAIL_SIZE); // This assumes you've included the method I mentioned above for optimization
ImageView image = (ImageView) findViewById(R.id.imgLoaded);
image.setImageBitmap(thumbnail);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.