如何拍照以显示在`ImageView`中并保存图片?
Posted
技术标签:
【中文标题】如何拍照以显示在`ImageView`中并保存图片?【英文标题】:How to take a picture to show in a `ImageView` and save the picture? 【发布时间】:2015-10-05 08:45:03 【问题描述】:我需要用camera
拍一张图片,保存图片,显示在ImageView
,当我点击Imageview
时显示在全屏模式。
以后需要把图片发到internet
。
这就是我所做的:
public void captureImage(View v)
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
imgView = (ImageView) findViewById(R.id.formRegister_picture);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
case CAMERA_PIC_REQUEST:
if(resultCode==RESULT_OK)
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imgView.setImageBitmap(thumbnail);
【问题讨论】:
【参考方案1】:您可以通过在代码中添加这些行来调用相机活动:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
private static int RESULT_IMAGE_CLICK = 1;
cameraImageUri = getOutputMediaFileUri(1);
// set the image file name
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
startActivityForResult(intent, RESULT_IMAGE_CLICK);
现在创建文件Uri
,因为在某些安卓手机中,您会在return
中获得null
数据
所以这里是获取图片URI
的方法:
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type)
return Uri.fromFile(getOutputMediaFile(type));
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type)
// Check that the SDCard is mounted
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES);
// Create the storage directory(MyCameraVideo) if it does not exist
if (!mediaStorageDir.exists())
if (!mediaStorageDir.mkdirs())
Log.e("Item Attachment",
"Failed to create directory MyCameraVideo.");
return null;
java.util.Date date = new java.util.Date();
String timeStamp = getTimeStamp();
File mediaFile;
if (type == 1)
// For unique video file name appending current timeStamp with file
// name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +abc+ ".jpg");
else
return null;
return mediaFile;
用于检索点击的图像:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
if (requestCode == RESULT_IMAGE_CLICK)
// Here you have the ImagePath which you can set to you image view
Log.e("Image Name", cameraImageUri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(cameraImageUri.getPath());
yourImageView.setImageBitmap(myBitmap);
// For further image Upload i suppose your method for image upload is UploadImage
File imageFile = new File(cameraImageUri.getPath());
uploadImage(imageFile);
【讨论】:
getExternalStorageDirectory
现已弃用,应在此处使用上下文【参考方案2】:
MainActivity.class
package edu.gvsu.cis.masl.camerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MyCameraActivity extends Activity
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
);
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_
android:layout_
android:text="@string/photo" >
</Button>
<ImageView
android:id="@+id/imageView1"
android:layout_
android:layout_
android:src="@drawable/icon" >
</ImageView>
</LinearLayout>
确保您的所有 id 都是正确的。
有什么想知道的,欢迎联系我。
【讨论】:
【参考方案3】:由于没有适当的解决方案,我将把我整理的有效且正确的东西放在这里。
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
takepic.setOnClickListener(new View.OnClickListener()
public void onClick(View v) Intent intent = new Intent();
addPhoto();
);
Android 清单:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
Android Manifest 再次在顶部:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
外部 res/xml/file_paths.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" />
</paths>
创建图像文件函数
private File createImageFile() throws IOException
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
添加照片功能
private void addPhoto()
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getActivity().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam)
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.MEDIA_IGNORE_FILENAME, ".nomedia");
cameraIntents.add(intent);
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "profileimg");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]));
File photoFile = null;
try
photoFile = createImageFile();
catch (IOException ex)
// Error occurred while creating the File
// Continue only if the File was successfully created
if (photoFile != null)
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(chooserIntent, 100);
关于活动回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100)
try
Bundle extras = data.getExtras();
Uri uri = data.getData();
ImageButton takepic = (ImageButton) returnView.findViewById(R.id.takepic);
if (extras!=null)
Bitmap imageBitmap = (Bitmap) extras.get("data");
Log.d(TAG, "onActivityResult: "+mCurrentPhotoPath);
takepic.setImageBitmap(imageBitmap);
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String idx = wholeID.split(":")[1];
String[] column = MediaStore.Images.Media.DATA;
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContext().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]idx, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst())
filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
takepic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "Uploading In Progress",
Toast.LENGTH_LONG);
catch(Exception e)
e.getMessage();
【讨论】:
【参考方案4】:试试这个,将图像保存到文件资源管理器:
public void captureImage(View v)
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "image.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
public void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== Activity.RESULT_OK)
f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles())
if (temp.getName().equals("image.png"))
f = temp;
imagePath= f.getAbsolutePath();
Bitmap thumbnail= BitmapFactory.decodeFile(f.getAbsolutePath(), options);
imgView.setImageBitmap(thumbnail);
您可以在需要显示时从路径“imagePath”获取图像。
【讨论】:
以上是关于如何拍照以显示在`ImageView`中并保存图片?的主要内容,如果未能解决你的问题,请参考以下文章
我做了一个启动相机的PhoneGap应用程序,拍照并保存到SD卡。如何让该图片以 HTML 格式显示?