首页 > 代码库 > ImageView显示拍照or本地图片

ImageView显示拍照or本地图片

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" 6     android:paddingBottom="@dimen/activity_vertical_margin" 7     android:paddingLeft="@dimen/activity_horizontal_margin" 8     android:paddingRight="@dimen/activity_horizontal_margin" 9     android:paddingTop="@dimen/activity_vertical_margin"10     tools:context="com.example.imageview.MainActivity" >11 12     <Button   13         android:layout_width="fill_parent" 14         android:layout_height="wrap_content"  15         android:text="选择图片" 16         android:id="@+id/selectImage" 17         />    18     <Button   19         android:layout_width="fill_parent"  20         android:layout_height="wrap_content"  21         android:text="拍照图片" 22         android:id="@+id/captureImage" 23         />    24     <ImageView25         android:id="@+id/imageView"26         android:maxHeight="1000dip"27         android:maxWidth="1000dip"28         android:layout_width="200dp"29         android:layout_height="200dp"30         android:layout_gravity="center_horizontal"31         android:scaleType="fitCenter" />32 33 </LinearLayout>
  1 package com.example.imageview;  2   3 import java.io.ByteArrayOutputStream;  4 import java.io.File;  5 import java.io.IOException;  6   7 import android.app.Activity;  8 import android.app.AlertDialog;  9 import android.app.AlertDialog.Builder; 10 import android.app.Dialog; 11 import android.content.ContentResolver; 12 import android.content.DialogInterface; 13 import android.content.Intent; 14 import android.database.Cursor; 15 import android.graphics.Bitmap; 16 import android.graphics.BitmapFactory; 17 import android.net.Uri; 18 import android.os.Bundle; 19 import android.os.Environment; 20 import android.provider.MediaStore; 21 import android.util.Log; 22 import android.view.Menu; 23 import android.view.MenuItem; 24 import android.view.View; 25 import android.view.View.OnClickListener; 26 import android.widget.Button; 27 import android.widget.ImageView; 28 import android.widget.Toast; 29  30  31 public class MainActivity extends Activity implements OnClickListener { 32  33     private Button selectImage, uploadImage,captureImage; 34     private ImageView imageView; 35     private Bitmap photo = null; 36     private String picPath = null; 37     private File file = null; 38      39     @Override 40     protected void onCreate(Bundle savedInstanceState) { 41         super.onCreate(savedInstanceState); 42         setContentView(R.layout.activity_main); 43          44         selectImage = (Button) this.findViewById(R.id.selectImage); 45         captureImage=(Button) this.findViewById(R.id.captureImage); 46         selectImage.setOnClickListener(this); 47         uploadImage.setOnClickListener(this); 48         captureImage.setOnClickListener(this); 49         imageView = (ImageView) this.findViewById(R.id.imageView); 50     } 51  52     @Override 53     public void onClick(View v) { 54         // TODO Auto-generated method stub 55         switch (v.getId()) { 56             case R.id.selectImage:  57                 Intent intent = new Intent(); 58                 intent.setType("image/*"); 59                 intent.setAction(Intent.ACTION_GET_CONTENT); 60                 startActivityForResult(intent, 1); 61                 break; 62             case R.id.captureImage:  //照相后显示图片 63                 destoryBimap();   64                 String state = Environment.getExternalStorageState();   65                 if (state.equals(Environment.MEDIA_MOUNTED)) {   66                     String saveDir = Environment.getExternalStorageDirectory()   67                          + "/temple";   68                  File dir = new File(saveDir);   69                  if (!dir.exists()) {   70                      dir.mkdir();   71                  }   72                  file = new File(saveDir, "temp.jpg");   73                  file.delete();   74                  if (!file.exists()) {   75                      try {   76                          file.createNewFile();   77                      } catch (IOException e) {   78                          e.printStackTrace();   79                          Toast.makeText(this,"创建临时文件失败",Toast.LENGTH_LONG).show();   80                          return;   81                      }   82                  }   83                  Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);   84                  intents.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));   85                  startActivityForResult(intents, 2);   86              } else {   87                  Toast.makeText(this,"存储卡不存在" , Toast.LENGTH_LONG)  .show();   88              }   89             break;     90         default: 91             break; 92         } 93     } 94      95     private void destoryBimap()  96     {     97         imageView.setImageBitmap(null);   98         if (photo != null && !photo.isRecycled()) {     99             photo.recycle();     //回收内存,一定要将 imageView中图片设置成null100             photo = null;    101         }    102     }103 104     @Override105     protected void onActivityResult(int requestCode, int resultCode, Intent data) {106         if (requestCode ==1) {   107             if (data != null) {108                 Uri uri = data.getData();109                 try { 110                     String[] pojo = { MediaStore.Images.Media.DATA };111                     Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);112                     ContentResolver cr = this.getContentResolver();113                     int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);114                     cursor.moveToFirst();115                     String path = cursor.getString(colunm_index);116 117                     if (path.endsWith("jpg") || path.endsWith("png")) {118                         picPath = path;119                         Log.e("图片路径", picPath);120                         121                         //Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));122                         //imageView.setImageBitmap(bitmap);123                         //Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr, uri);    124                         125                         Bitmap bitmap = BitmapFactory.decodeFile(picPath);126                         imageView.setImageBitmap(bitmap);127                         Toast.makeText(this, "图片路径"+ picPath, 1000).show();128                     } 129                     else {130                         alert("您选择的不是有效的图片");131                     }    132                 } catch (Exception e) {133                     alert("选择图片错误");134                 }135             }136             else{137                 alert("data is null");138             }139         }140         else if (requestCode ==2){    //拍照后执行    141               if (file != null && file.exists()) {  142                     BitmapFactory.Options options = new BitmapFactory.Options();  143                     options.inSampleSize = 2;  144                     photo = BitmapFactory.decodeFile(file.getPath(), options);  145                     imageView.setImageBitmap(photo);  146                     //picPath = file.getPath();  147                 } else {  148                     alert("拍照错误");149                 }              150         }151             152         super.onActivityResult(requestCode, resultCode, data);153     }154     155     private void alert(String str) {156         Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")157                 .setMessage(str)158                 .setPositiveButton("确定", new DialogInterface.OnClickListener() {159                     public void onClick(DialogInterface dialog, int which) {160                         picPath = null;161                     }162                 }).create();163         dialog.show();164     }165 }
 1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3     package="com.example.imageview" 4     android:versionCode="1" 5     android:versionName="1.0" > 6  7     <uses-sdk 8         android:minSdkVersion="16" 9         android:targetSdkVersion="18" />10     11     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>12     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>13 14     <application15         android:allowBackup="true"16         android:icon="@drawable/ic_launcher"17         android:label="@string/app_name"18         android:theme="@style/AppTheme" >19         <activity20             android:name=".MainActivity"21             android:label="@string/app_name" >22             <intent-filter>23                 <action android:name="android.intent.action.MAIN" />24 25                 <category android:name="android.intent.category.LAUNCHER" />26             </intent-filter>27         </activity>28     </application>29 30 </manifest>

 

ImageView显示拍照or本地图片