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

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

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

Java代码 复制代码 收藏代码
  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代码 复制代码 收藏代码
  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.  
  10.         final AlertDialog.Builder builder = new AlertDialog.Builder( 
  11.                 dialogContext); 
  12.         builder.setTitle("添加图片"); 
  13.         builder.setSingleChoiceItems(adapter, -1
  14.                 new DialogInterface.OnClickListener() { 
  15.                     public void onClick(DialogInterface dialog, int which) { 
  16.                         dialog.dismiss(); 
  17.                         switch (which) { 
  18.                         case 0: { 
  19.                             String status = Environment 
  20.                                     .getExternalStorageState(); 
  21.                             if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡 
  22.                                 Intent i = new Intent( 
  23.                                         MediaStore.ACTION_IMAGE_CAPTURE); 
  24.                                 capturefile = new File(PHOTO_DIR, 
  25.                                         getPhotoFileName()); 
  26.                                 try
  27.                                     capturefile.createNewFile(); 
  28.                                     i.putExtra(MediaStore.EXTRA_OUTPUT, 
  29.                                             Uri.fromFile(capturefile));//将拍摄的照片信息存到capturefile中 
  30.                                 } catch (IOException e) { 
  31.                                     // TODO Auto-generated catch block 
  32.                                     e.printStackTrace(); 
  33.                                 } 
  34.  
  35.                                 startActivityForResult(i, PHOTO_WITH_CAMERA);// 用户点击了从照相机获取 
  36.                             } else
  37.                                 showToast("没有SD卡"); 
  38.                             } 
  39.                             break
  40.  
  41.                         } 
  42.                         case 1:// 从相册中去获取 
  43.                             Intent intent = new Intent(); 
  44.                             /* 开启Pictures画面Type设定为image */ 
  45.                             intent.setType("image/*"); 
  46.                             /* 使用Intent.ACTION_GET_CONTENT这个Action */ 
  47.                             intent.setAction(Intent.ACTION_GET_CONTENT); 
  48.                             /* 取得相片后返回本画面 */ 
  49.                             startActivityForResult(intent, PHOTO_WITH_DATA); 
  50.                             break
  51.                         } 
  52.                     } 
  53.                 }); 
  54.     builder.create().show(); 
  55.     } 
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代码 复制代码 收藏代码
  1. /*
  2.      * 通过相机回传图片的文件名
  3.      */ 
  4.     private String getPhotoFileName() { 
  5.         Date date = new Date(System.currentTimeMillis()); 
  6.         SimpleDateFormat dateFormat = new SimpleDateFormat( 
  7.                 "'IMG'_yyyyMMdd_HHmmss"); 
  8.         return dateFormat.format(date) + ".jpg"
  9.     } 
/*
	 * 通过相机回传图片的文件名
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

再来看OnActivityResult

Java代码 复制代码 收藏代码
  1. /*
  2.      * 选择图片的回传处理
  3.      */ 
  4.     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  5.         File file = null
  6.         Bitmap pic = null
  7.         if (resultCode == RESULT_OK) { 
  8.             switch (requestCode) { 
  9.             case PHOTO_WITH_CAMERA://获取拍摄的文件 
  10.                 picPath = capturefile.getAbsolutePath(); 
  11.                 System.out.println(picPath); 
  12.                 file = new File(picPath); 
  13.                 pic = decodeFile(file); 
  14.                 thumbimage.setImageBitmap(pic); 
  15.                 System.out.println("++++++相机+++++"); 
  16.                 break
  17.  
  18.             case PHOTO_WITH_DATA://获取从图库选择的文件 
  19.                 Uri uri = data.getData(); 
  20.                 String scheme = uri.getScheme(); 
  21.                 if (scheme.equalsIgnoreCase("file")) { 
  22.                     picPath = uri.getPath(); 
  23.                     System.out.println(picPath); 
  24.                     file = new File(picPath); 
  25.                     pic = decodeFile(file); 
  26.                     thumbimage.setImageBitmap(pic); 
  27.                 } else if (scheme.equalsIgnoreCase("content")) { 
  28.                     Cursor cursor = getContentResolver().query(uri, null, null
  29.                             null, null); 
  30.                     cursor.moveToFirst(); 
  31.                     picPath = cursor.getString(1); 
  32.                     file = new File(picPath); 
  33.                     pic = decodeFile(file); 
  34.                     thumbimage.setImageBitmap(pic); 
  35.                 } 
  36.                 break
  37.             } 
  38.  
  39.         } 
  40.         super.onActivityResult(requestCode, resultCode, data); 
  41.     } 
/*
	 * 选择图片的回传处理
	 */
	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代码 复制代码 收藏代码
  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代码 复制代码 收藏代码
  1. /*
  2.      * 压缩图片,避免内存不足报错
  3.      */ 
  4.     private Bitmap decodeFile(File f) { 
  5.         Bitmap b = null
  6.         try
  7.             // Decode image size 
  8.             BitmapFactory.Options o = new BitmapFactory.Options(); 
  9.             o.inJustDecodeBounds = true
  10.  
  11.             FileInputStream fis = new FileInputStream(f); 
  12.             BitmapFactory.decodeStream(fis, null, o); 
  13.             fis.close(); 
  14.  
  15.             int scale = 1
  16.             if (o.outHeight > 100 || o.outWidth > 100) { 
  17.                 scale = (int) Math.pow( 
  18.                         2
  19.                         (int) Math.round(Math.log(100 / (double) Math.max( 
  20.                                 o.outHeight, o.outWidth)) / Math.log(0.5))); 
  21.             } 
  22.  
  23.             // Decode with inSampleSize 
  24.             BitmapFactory.Options o2 = new BitmapFactory.Options(); 
  25.             o2.inSampleSize = scale; 
  26.             fis = new FileInputStream(f); 
  27.             b = BitmapFactory.decodeStream(fis, null, o2); 
  28.             fis.close(); 
  29.         } catch (IOException e) { 
  30.             e.printStackTrace(); 
  31.         } 
  32.         return b; 
  33.     } 
/*
	 * 压缩图片,避免内存不足报错
	 */
	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;
	}

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

分享到:     
评论
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值