在imageView动态显示相册和拍照图片

本文展示了如何在Android应用中实现在imageView上动态显示从相册选择或相机拍摄的图片。通过Intent调用系统相册和相机应用,获取图片后进行处理并显示,同时提供了权限管理和异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

view 代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"     
    >
    <Button   
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"  
    android:text="选择图片" 
    android:id="@+id/selectImage" 
    />    
     <Button   
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="拍照图片" 
    android:id="@+id/captureImage" 
    />    
    <Button   
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="上传图片" 
    android:id="@+id/uploadImage" 
    /> 
     <ImageView
         android:id="@+id/imageView"
         android:maxHeight="1000dip"
         android:maxWidth="1000dip"
         android:layout_width="200dp"
         android:layout_height="200dp"
         android:layout_gravity="center_horizontal"
         android:scaleType="fitXY" />
</LinearLayout>

后台代码如下:

package com.example.uploadfile;

import java.io.File;
import java.io.IOException;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
private Button selectImage, uploadImage,captureImage;
private ImageView imageView;
private Bitmap photo=null;
private String picPath = null;
private File file=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectImage = (Button) this.findViewById(R.id.selectImage);
uploadImage = (Button) this.findViewById(R.id.uploadImage);
captureImage=(Button) this.findViewById(R.id.captureImage);
selectImage.setOnClickListener(this);
uploadImage.setOnClickListener(this);
captureImage.setOnClickListener(this);
imageView = (ImageView) this.findViewById(R.id.imageView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
public void onClick(View v) {
switch (v.getId()) {

case R.id.selectImage:  //从相册中选择图片

/***
* 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的
*/

Intent intent = new Intent();

intent.setType("image/*");

//intent.setAction(Intent.ACTION_PICK); //直接从相册选择
 
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);

break;
case R.id.captureImage:  //照相后显示图片
destoryBimap();  
String state = Environment.getExternalStorageState();  
if (state.equals(Environment.MEDIA_MOUNTED)) {  
    String saveDir = Environment.getExternalStorageDirectory()  
            + "/temple";  
    File dir = new File(saveDir);  
    if (!dir.exists()) {  
        dir.mkdir();  
    }  
    file = new File(saveDir, "temp.jpg");  
    file.delete();  
    if (!file.exists()) {  
        try {  
            file.createNewFile();  
        } catch (IOException e) {  
            e.printStackTrace();  
            Toast.makeText(this,"创建临时文件失败",Toast.LENGTH_LONG).show();  
            return;  
        }  
    }  
    Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
    intents.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));  
    startActivityForResult(intents, 2);  
} else {  
    Toast.makeText(this,"存储卡不存在" , Toast.LENGTH_LONG)  .show();  
}  
break;
default:

break;
}

}
//回收内存
private void destoryBimap() {    
        imageView.setImageBitmap(null);  
        if (photo != null && !photo.isRecycled()) {    
            photo.recycle();     //回收内存,一定要将 imageView中图片设置成null
            photo = null;    
        }    
}  

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode ==1) {   //从相册选择图片后执行

if (data != null) {

/**
* 当选择的图片不为空的话,在获取到图片的途径
*/

Uri uri = data.getData();

//Log.e(TAG, "uri = " + uri);

try {  //从相册返回的url 

String[] pojo = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(uri, pojo, null, null, null);

if (cursor != null) {

ContentResolver cr = this.getContentResolver();

int colunm_index = cursor

.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

cursor.moveToFirst();

String path = cursor.getString(colunm_index);

/***
* 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,
* 你选择的文件就不一定是图片了,
* 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以
*/

if (path.endsWith("jpg") || path.endsWith("png")) {

picPath = path;
Log.e("图片路径", picPath);
//Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));

//imageView.setImageBitmap(bitmap);
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, uri);    
Bitmap bitmap = BitmapFactory.decodeFile(picPath);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, "图片路径"+picPath, 1000).show();

} else {

alert("您选择的不是有效的图片");

}

} else {  //从第三方软件返回的路径

ContentResolver cr = this.getContentResolver();
String path =uri.getPath();
if (path.endsWith("jpg") || path.endsWith("png")) {

picPath = path;
Log.e("图片路径", picPath);
//Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));

Bitmap bitmap = BitmapFactory.decodeFile(picPath);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, "图片路径"+picPath, 1000).show();

} else {

alert("您选择的不是有效的图片");

}
}

} catch (Exception e) {

alert("选择图片错误");
}

}
else{
alert("data is null");
}
}
else if (requestCode ==2){ //拍照后执行
 if (file != null && file.exists()) {  
               BitmapFactory.Options options = new BitmapFactory.Options();  
               options.inSampleSize = 2;  
               photo = BitmapFactory.decodeFile(file.getPath(), options);  
               imageView.setImageBitmap(photo);  
               picPath = file.getPath();  
               
           } else {  
            alert("拍照错误");
           }  
}
super.onActivityResult(requestCode, resultCode, data);

}
        
         //消息提示
private void alert(String str) {

Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")

.setMessage(str)

.setPositiveButton("确定", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
picPath = null;
}
}).create();
dialog.show();
}
}

AndroidManifest.xml 文件类容如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uploadfile"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17" />

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application  android:hardwareAccelerated="false"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.uploadfile.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
在imageView动态显示相册和拍照图片 - chy2z - 黑暗行动
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值