天天看点

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)

     之前已经介绍了如何发布一条文字微博,接下来的两篇文章会介绍如何发送带图片的微博。今天先看如何调用照相或者Gallery来获取我们想要发送图片文件。

第一步,看需要申明的几个值

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1. private String picPath;//文件路径 
  2.     private static final int PHOTO_WITH_CAMERA = 1010;// 拍摄照片 
  3.     private static final int PHOTO_WITH_DATA = 1020;// 从SD中得到照片 
  4.     private static final File PHOTO_DIR = new File( 
  5.             Environment.getExternalStorageDirectory() + "/DCIM/Camera");//拍摄照片存储的文件夹路劲 
  6.     private File capturefile;//拍摄的照片文件 
private String picPath;//文件路径
	private static final int PHOTO_WITH_CAMERA = 1010;// 拍摄照片
	private static final int PHOTO_WITH_DATA = 1020;// 从SD中得到照片
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");//拍摄照片存储的文件夹路劲
	private File capturefile;//拍摄的照片文件
           

第二步,选择获取图片方式的对话框实现

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1. final Context dialogContext = new ContextThemeWrapper(context, 
  2.                 android.R.style.Theme_Light); 
  3.         String[] choices; 
  4.         choices = new String[2]; 
  5.         choices[0] = "相机拍摄"; // 拍照 
  6.         choices[1] = "本地相册"; // 从相册中选择 
  7.         final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, 
  8.                 android.R.layout.simple_list_item_1, choices); 
  9.         final AlertDialog.Builder builder = new AlertDialog.Builder( 
  10.                 dialogContext); 
  11.         builder.setTitle("添加图片"); 
  12.         builder.setSingleChoiceItems(adapter, -1, 
  13.                 new DialogInterface.OnClickListener() { 
  14.                     public void onClick(DialogInterface dialog, int which) { 
  15.                         dialog.dismiss(); 
  16.                         switch (which) { 
  17.                         case 0: { 
  18.                             String status = Environment 
  19.                                     .getExternalStorageState(); 
  20.                             if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡 
  21.                                 Intent i = new Intent( 
  22.                                         MediaStore.ACTION_IMAGE_CAPTURE); 
  23.                                 capturefile = new File(PHOTO_DIR, 
  24.                                         getPhotoFileName()); 
  25.                                 try { 
  26.                                     capturefile.createNewFile(); 
  27.                                     i.putExtra(MediaStore.EXTRA_OUTPUT, 
  28.                                             Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中 
  29.                                 } catch (IOException e) { 
  30.                                     // TODO Auto-generated catch block 
  31.                                     e.printStackTrace(); 
  32.                                 } 
  33.                                 startActivityForResult(i, PHOTO_WITH_CAMERA);// 用户点击了从照相机获取 
  34.                             } else { 
  35.                                 showToast("没有SD卡"); 
  36.                             } 
  37.                             break; 
  38.                         } 
  39.                         case 1:// 从相册中去获取 
  40.                             Intent intent = new Intent(); 
  41.                             intent.setType("image 
  42.                             intent.setAction(Intent.ACTION_GET_CONTENT); 
  43.                             startActivityForResult(intent, PHOTO_WITH_DATA); 
  44.                             break; 
  45.                         } 
  46.                     } 
  47.                 }); 
  48.     builder.create().show(); 
  49.     } 
final Context dialogContext = new ContextThemeWrapper(context,
				android.R.style.Theme_Light);
		String[] choices;
		choices = new String[2];
		choices[0] = "相机拍摄"; // 拍照
		choices[1] = "本地相册"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("添加图片");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0: {
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								Intent i = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								capturefile = new File(PHOTO_DIR,
										getPhotoFileName());
								try {
									capturefile.createNewFile();
									i.putExtra(MediaStore.EXTRA_OUTPUT,
											Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								startActivityForResult(i, PHOTO_WITH_CAMERA);// 用户点击了从照相机获取
							} else {
								showToast("没有SD卡");
							}
							break;

						}
						case 1:// 从相册中去获取
							Intent intent = new Intent();
							/* 开启Pictures画面Type设定为image */
							intent.setType("image/*");
							/* 使用Intent.ACTION_GET_CONTENT这个Action */
							intent.setAction(Intent.ACTION_GET_CONTENT);
							/* 取得相片后返回本画面 */
							startActivityForResult(intent, PHOTO_WITH_DATA);
							break;
						}
					}
				});
	builder.create().show();
	}
           

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1.     private String getPhotoFileName() { 
  2.         Date date = new Date(System.currentTimeMillis()); 
  3.         SimpleDateFormat dateFormat = new SimpleDateFormat( 
  4.                 "'IMG'_yyyyMMdd_HHmmss"); 
  5.         return dateFormat.format(date) + ".jpg"; 
  6.     } 
/*
	 * 通过相机回传图片的文件名
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}
           

再来看OnActivityResult

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1.     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  2.         File file = null; 
  3.         Bitmap pic = null; 
  4.         if (resultCode == RESULT_OK) { 
  5.             switch (requestCode) { 
  6.             case PHOTO_WITH_CAMERA://获取拍摄的文件 
  7.                 picPath = capturefile.getAbsolutePath(); 
  8.                 System.out.println(picPath); 
  9.                 file = new File(picPath); 
  10.                 pic = decodeFile(file); 
  11.                 thumbimage.setImageBitmap(pic); 
  12.                 System.out.println("++++++相机+++++"); 
  13.                 break; 
  14.             case PHOTO_WITH_DATA://获取从图库选择的文件 
  15.                 Uri uri = data.getData(); 
  16.                 String scheme = uri.getScheme(); 
  17.                 if (scheme.equalsIgnoreCase("file")) { 
  18.                     picPath = uri.getPath(); 
  19.                     System.out.println(picPath); 
  20.                     file = new File(picPath); 
  21.                     pic = decodeFile(file); 
  22.                     thumbimage.setImageBitmap(pic); 
  23.                 } else if (scheme.equalsIgnoreCase("content")) { 
  24.                     Cursor cursor = getContentResolver().query(uri, null, null, 
  25.                             null, null); 
  26.                     cursor.moveToFirst(); 
  27.                     picPath = cursor.getString(1); 
  28.                     file = new File(picPath); 
  29.                     pic = decodeFile(file); 
  30.                     thumbimage.setImageBitmap(pic); 
  31.                 } 
  32.                 break; 
  33.             } 
  34.         } 
  35.         super.onActivityResult(requestCode, resultCode, data); 
  36.     } 
/*
	 * 选择图片的回传处理
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		File file = null;
		Bitmap pic = null;
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PHOTO_WITH_CAMERA://获取拍摄的文件
				picPath = capturefile.getAbsolutePath();
				System.out.println(picPath);
				file = new File(picPath);
				pic = decodeFile(file);
				thumbimage.setImageBitmap(pic);
				System.out.println("++++++相机+++++");
				break;

			case PHOTO_WITH_DATA://获取从图库选择的文件
				Uri uri = data.getData();
				String scheme = uri.getScheme();
				if (scheme.equalsIgnoreCase("file")) {
					picPath = uri.getPath();
					System.out.println(picPath);
					file = new File(picPath);
					pic = decodeFile(file);
					thumbimage.setImageBitmap(pic);
				} else if (scheme.equalsIgnoreCase("content")) {
					Cursor cursor = getContentResolver().query(uri, null, null,
							null, null);
					cursor.moveToFirst();
					picPath = cursor.getString(1);
					file = new File(picPath);
					pic = decodeFile(file);
					thumbimage.setImageBitmap(pic);
				}
				break;
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
           

这里需要注意的是,从Gallery返回的内容,分为了两种情况。在模拟器上,我们可以发现返回的内容模式为"content”而从某些手机的操作例如MIUI,返回的scheme为"file"。同样,在MIUI上返回的照相内容依旧为file,但是可以通过通用方法,将照相的信息写入到我们制定的文件当中。也就是上面代码中的这两句

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1. Intent i = new Intent( 
  2.                                         MediaStore.ACTION_IMAGE_CAPTURE); 
  3.                                 capturefile = new File(PHOTO_DIR, 
  4.                                         getPhotoFileName()); 
  5.                                 try { 
  6.                                     capturefile.createNewFile(); 
  7.                                     i.putExtra(MediaStore.EXTRA_OUTPUT, 
  8.                                             Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中 
  9.                                 } catch (IOException e) { 
  10.                                     // TODO Auto-generated catch block 
  11.                                     e.printStackTrace(); 
  12.                                 } 
Intent i = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								capturefile = new File(PHOTO_DIR,
										getPhotoFileName());
								try {
									capturefile.createNewFile();
									i.putExtra(MediaStore.EXTRA_OUTPUT,
											Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
           

在之前的文章中,我们为发送微博页面设计了一个ImageView用来显示选取的照片。但是我们发现,如果不对返回的照片做处理,那么在第二次选择照片的时候系统会抛出内存溢出的错误。网上对这个问题的解释是,android只为每个程序分配8M的缓存,所以图片不经过压缩就会抛出异常。那么我们把图片压缩之后再显示在ImageView当中,压缩方法如下:

Java代码

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
  1.     private Bitmap decodeFile(File f) { 
  2.         Bitmap b = null; 
  3.         try { 
  4.             // Decode image size 
  5.             BitmapFactory.Options o = new BitmapFactory.Options(); 
  6.             o.inJustDecodeBounds = true; 
  7.             FileInputStream fis = new FileInputStream(f); 
  8.             BitmapFactory.decodeStream(fis, null, o); 
  9.             fis.close(); 
  10.             int scale = 1; 
  11.             if (o.outHeight > 100 || o.outWidth > 100) { 
  12.                 scale = (int) Math.pow( 
  13.                         2, 
  14.                         (int) Math.round(Math.log(100 / (double) Math.max( 
  15.                                 o.outHeight, o.outWidth)) / Math.log(0.5))); 
  16.             } 
  17.             // Decode with inSampleSize 
  18.             BitmapFactory.Options o2 = new BitmapFactory.Options(); 
  19.             o2.inSampleSize = scale; 
  20.             fis = new FileInputStream(f); 
  21.             b = BitmapFactory.decodeStream(fis, null, o2); 
  22.             fis.close(); 
  23.         } catch (IOException e) { 
  24.             e.printStackTrace(); 
  25.         } 
  26.         return b; 
  27.     } 
/*
	 * 压缩图片,避免内存不足报错
	 */
	private Bitmap decodeFile(File f) {
		Bitmap b = null;
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			FileInputStream fis = new FileInputStream(f);
			BitmapFactory.decodeStream(fis, null, o);
			fis.close();

			int scale = 1;
			if (o.outHeight > 100 || o.outWidth > 100) {
				scale = (int) Math.pow(
						2,
						(int) Math.round(Math.log(100 / (double) Math.max(
								o.outHeight, o.outWidth)) / Math.log(0.5)));
			}

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			fis = new FileInputStream(f);
			b = BitmapFactory.decodeStream(fis, null, o2);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
           

至此,我们完成了对图片的选择,下一篇文章会通过新浪指定的方法,实现将图片上传到微博,也就是发送一条带图片的微博。

分享到:     

Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)
Android:SNS客户端开发七:发送带图片的微博(一)(调用相机和Gallery获得照片)

Android:SNS客户端开发八:发送带图片的 ...      |      Android:SNS客户端开发六:发送一条文字 ...

  • 2011-12-07 14:42
  • 浏览 783
  • 评论(3)
  • 分类:移动开发
  • 相关推荐
评论

3 楼    codeMoe    2012-03-21            还有个问题,我显示图片时,为什么都是将本来应该竖着显示的图片,变为横着显示,压缩后照片很多锯齿 2 楼    codeMoe    2012-03-21            codeMoe 写道 ntent i = new Intent( 

                                        MediaStore.ACTION_IMAGE_CAPTURE); 

                                capturefile = new File(PHOTO_DIR, 

                                        getPhotoFileName()); 

                                try { 

                                    capturefile.createNewFile(); 

                                    i.putExtra(MediaStore.EXTRA_OUTPUT, 

                                            Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中 

                                } catch (IOException e) { 

                                    // TODO Auto-generated catch block 

                                    e.printStackTrace(); 

                                } 

请问这段是在什么时候调用

额。。不好意思,是我没仔细看,就在那拍照哪里调用 1 楼    codeMoe    2012-03-21            ntent i = new Intent( 

                                        MediaStore.ACTION_IMAGE_CAPTURE); 

                                capturefile = new File(PHOTO_DIR, 

                                        getPhotoFileName()); 

                                try { 

                                    capturefile.createNewFile(); 

                                    i.putExtra(MediaStore.EXTRA_OUTPUT, 

                                            Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中 

                                } catch (IOException e) { 

                                    // TODO Auto-generated catch block 

                                    e.printStackTrace(); 

                                } 

请问这段是在什么时候调用

发表评论

转自:http://river418.iteye.com/blog/1295836