关闭

android通过拍照、相册获取图片并显示

627人阅读 评论(0) 收藏 举报

摘自:http://www.haolizi.net/example/view_2963.html


【核心代码】


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
public class MainActivity extends Activity{
     
    private static final int PHOTO_WITH_DATA = 18//从SD卡中得到图片
    private static final int PHOTO_WITH_CAMERA = 37;// 拍摄照片
     
    private Button btn_open;
    private ImageView iv_temp;
    private Dialog dialog_pic;
     
    private String imgPath  = "";
    private String imgName = "";
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        iv_temp = (ImageView) findViewById(R.id.imageView);
        iv_temp.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openPictureDialog();
            }
        });
        btn_open = (Button) findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openPictureSelectDialog();
            }
        });
    }
    /**打开对话框**/
    private void openPictureSelectDialog() {
        //自定义Context,添加主题
        Context dialogContext = new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Light);
        String[] choiceItems= new String[2];
        choiceItems[0] = "相机拍摄"//拍照
        choiceItems[1] = "本地相册"//从相册中选择
        ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1,choiceItems);
        //对话框建立在刚才定义好的上下文上
        AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
        builder.setTitle("添加图片");
        builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case 0//相机
                    doTakePhoto();
                    break;
                case 1//从图库相册中选取
                    doPickPhotoFromGallery();
                    break;
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }  
     
    /**打开图片查看对话框**/
    private void openPictureDialog() {
         
         
        dialog_pic = new Dialog(MainActivity.this,R.style.simple_dialog);
         
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.from(MainActivity.this).inflate(R.layout.dialog_picture, null);
         
        ImageView imgView = (ImageView) view.findViewById(R.id.img_weibo_img);
        Button btnBig = (Button) view.findViewById(R.id.btn_big);
        btnBig.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ImgDisplayActivity.class);
                imgPath = getApplicationContext().getFilesDir() "/" imgName;
                intent.putExtra("imgUrl", imgPath); //将图片的路径传递过去
                startActivity(intent);
            }
        });
         
         
         
         
        dialog_pic.setContentView(view);
        dialog_pic.show();
         
        displayForDlg(imgView,imgPath,btnBig); //显示内容到dialog中
         
    }
     
    private void displayForDlg(ImageView imgView, String imgPath2,Button btnBig) {
        imgView.setVisibility(View.VISIBLE);
        btnBig.setVisibility(View.VISIBLE);
        imgPath = getApplicationContext().getFilesDir() "/" imgName;
        System.out.println("图片文件路径----------》" imgPath);
        if(!imgPath.equals("")) {
            Bitmap tempBitmap = BitmapFactory.decodeFile(imgPath);
            imgView.setImageBitmap(tempBitmap);//显示图片
        }
    }
    /**You will receive this call immediately before onResume() when your activity is re-starting.**/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        
        if(resultCode == RESULT_OK) {  //返回成功
            switch (requestCode) {
            case PHOTO_WITH_CAMERA:  {//拍照获取图片
                String status = Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)) { //是否有SD卡
                     
                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() "/image.jpg");
                     
                    imgName = createPhotoFileName();
                    //写一个方法将此文件保存到本应用下面啦
                    savePicture(imgName,bitmap);
 
                    if (bitmap != null) {
                        //为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
                        Bitmap smallBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / 5, bitmap.getHeight() / 5);
                         
                        iv_temp.setImageBitmap(smallBitmap);
                    }
                    Toast.makeText(MainActivity.this, "已保存本应用的files文件夹下", Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(MainActivity.this, "没有SD卡", Toast.LENGTH_LONG).show();
                }
                break;
            }
                case PHOTO_WITH_DATA:  {//从图库中选择图片
                    ContentResolver resolver = getContentResolver();
                    //照片的原始资源地址
                    Uri originalUri = data.getData(); 
                    //System.out.println(originalUri.toString());  //" content://media/external/images/media/15838 "
 
//                  //将原始路径转换成图片的路径
//                  String selectedImagePath = uri2filePath(originalUri); 
//                  System.out.println(selectedImagePath);  //" /mnt/sdcard/DCIM/Camera/IMG_20130603_185143.jpg "
                    try {
                         //使用ContentProvider通过URI获取原始图片
                        Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                         
                        imgName = createPhotoFileName();
                        //写一个方法将此文件保存到本应用下面啦
                        savePicture(imgName,photo);
                         
                        if (photo != null) {
                            //为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
                            Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / 5, photo.getHeight() / 5);
                             
                            iv_temp.setImageBitmap(smallBitmap);
                        }
//                      iv_temp.setImageURI(originalUri);   //在界面上显示图片
                        Toast.makeText(MainActivity.this, "已保存本应用的files文件夹下", Toast.LENGTH_LONG).show();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                break;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
     
    
    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");  // 开启Pictures画面Type设定为image
        intent.setAction(Intent.ACTION_GET_CONTENT); //使用Intent.ACTION_GET_CONTENT这个Action
        startActivityForResult(intent, PHOTO_WITH_DATA); //取得相片后返回到本画面
    }
      
    /**拍照获取相片**/
    private void doTakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
        
        Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
        //指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        
        //直接使用,没有缩小 
        startActivityForResult(intent, PHOTO_WITH_CAMERA);  //用户点击了从相机获取
    }
     
    /**创建图片不同的文件名**/
    private String createPhotoFileName() {
        String fileName = "";
        Date date = new Date(System.currentTimeMillis());  //系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        fileName = dateFormat.format(date)   ".jpg";
        return fileName;
    }
     
     /**获取文件路径**/
     public String uri2filePath(Uri uri) 
        
            String[] projection = {MediaStore.Images.Media.DATA }; 
            Cursor cursor = managedQuery(uri, projection, null, null, null); 
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
            cursor.moveToFirst(); 
            String path =  cursor.getString(column_index);
            return path; 
        
      
     /**保存图片到本应用下**/
     private void savePicture(String fileName,Bitmap bitmap) {
            
            FileOutputStream fos =null;
            try {//直接写入名称即可,没有会被自动创建;私有:只有本应用才能访问,重新内容写入会被覆盖
                fos = MainActivity.this.openFileOutput(fileName, Context.MODE_PRIVATE);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把图片写入指定文件夹中
                 
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(null != fos) {
                        fos.close();
                        fos = null;
                    }
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


http://www.haolizi.net/example/view_2963.html


【核心代码】


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
public class MainActivity extends Activity{
     
    private static final int PHOTO_WITH_DATA = 18//从SD卡中得到图片
    private static final int PHOTO_WITH_CAMERA = 37;// 拍摄照片
     
    private Button btn_open;
    private ImageView iv_temp;
    private Dialog dialog_pic;
     
    private String imgPath  = "";
    private String imgName = "";
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        iv_temp = (ImageView) findViewById(R.id.imageView);
        iv_temp.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openPictureDialog();
            }
        });
        btn_open = (Button) findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openPictureSelectDialog();
            }
        });
    }
    /**打开对话框**/
    private void openPictureSelectDialog() {
        //自定义Context,添加主题
        Context dialogContext = new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Light);
        String[] choiceItems= new String[2];
        choiceItems[0] = "相机拍摄"//拍照
        choiceItems[1] = "本地相册"//从相册中选择
        ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1,choiceItems);
        //对话框建立在刚才定义好的上下文上
        AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
        builder.setTitle("添加图片");
        builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case 0//相机
                    doTakePhoto();
                    break;
                case 1//从图库相册中选取
                    doPickPhotoFromGallery();
                    break;
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }  
     
    /**打开图片查看对话框**/
    private void openPictureDialog() {
         
         
        dialog_pic = new Dialog(MainActivity.this,R.style.simple_dialog);
         
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.from(MainActivity.this).inflate(R.layout.dialog_picture, null);
         
        ImageView imgView = (ImageView) view.findViewById(R.id.img_weibo_img);
        Button btnBig = (Button) view.findViewById(R.id.btn_big);
        btnBig.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ImgDisplayActivity.class);
                imgPath = getApplicationContext().getFilesDir() "/" imgName;
                intent.putExtra("imgUrl", imgPath); //将图片的路径传递过去
                startActivity(intent);
            }
        });
         
         
         
         
        dialog_pic.setContentView(view);
        dialog_pic.show();
         
        displayForDlg(imgView,imgPath,btnBig); //显示内容到dialog中