Android拍照,上传,预览综合

一时失言乱红尘 2022-08-02 09:48 316阅读 0赞

最近需要做手机拍照【两种方式:调用系统相机(博客最后);自己写照相机布局】,预览,上传功能。特地研究了下android的手机拍照。

参考地址:

http://blog.csdn.net/cfwdl/article/details/5746708

http://mjbb.iteye.com/blog/1018006

http://blog.csdn.net/hellogv/article/details/5962494

1、上传文件功能网上很多讲的,只要细心点,按照格式来写发送的数据,都是没有问题的。

2、预览使用Gallery和ImageSwitcher就行,我做的很简单(参考代码)。

-——————————————————————————————————————————————————————————-

修改内容:

  1. 1、照相功能使用系统自带照相机(自己写的照相机属性设置根据不同照相机会有问题,所以舍弃)
  2. 2、预览功能不再使用Gallery+ImageSwitcher;实用性不强,并且显示慢且卡。改用异步加载
  3. 3、上传图片时,对图片进行压缩,增加上传速度。
  4. 4、长按gridView进入编辑模式,批量删除图片。参考[http://aokunsang.iteye.com/blog/1668902][http_aokunsang.iteye.com_blog_1668902];
  5. 5、今天又做修改,之前写的压缩图片方法的竟然会变形(没有测试大的图片),修改后不会变形了。

以此,希望能做到最好的用户体验。

附上流程图:

dd3ee1af-b97b-31bb-b14d-0c06c6830f29.jpg

拍照功能: 【预览尺寸有知道的朋友留言告知。】

Java代码 收藏代码

  1. * 拍照
  2. * @author Administrator
  3. */
  4. ublic class TakePhotoAct extends Activity implements SurfaceHolder.Callback{
  5. private static String imgPath = Environment.getExternalStorageDirectory().getPath() + “/“+Const.imageDir;
  6. private SurfaceView surfaceView; //相机画布
  7. private SurfaceHolder surfaceHolder;
  8. private Button takePicView,exitView;
  9. private Camera mCamera; //照相机
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.main);
  14. /这里我在AndroidManifest.xml的activity中添加了android:theme=”@android:style/Theme.NoTitleBar.Fullscreen”
  15. /**
  16. * 隐藏状态栏和标题栏
  17. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  18. requestWindowFeature(Window.FEATURE_NO_TITLE);
  19. */
  20. //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //横屏
  21. /**
  22. * 获取Button并且设置事件监听
  23. */
  24. takePicView = (Button)this.findViewById(R.id.takepic);
  25. takePicView.setOnClickListener(TakePicListener);
  26. exitView = (Button)this.findViewById(R.id.exit);
  27. exitView.setOnClickListener(new OnClickListener() {
  28. @Override
  29. public void onClick(View v) {
  30. finish();
  31. }
  32. });
  33. surfaceView = (SurfaceView)this.findViewById(R.id.surface_camera);
  34. surfaceHolder = surfaceView.getHolder();
  35. surfaceHolder.addCallback(this);
  36. surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  37. checkSoftStage(); //首先检测SD卡是否存在
  38. }
  39. /**
  40. * 检测手机是否存在SD卡,网络连接是否打开
  41. */
  42. private void checkSoftStage(){
  43. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //判断是否存在SD卡
  44. / String rootPath = Environment.getExternalStorageDirectory().getPath(); //获取SD卡的根目录
  45. File file = new File(imgPath);
  46. if(!file.exists()){
  47. file.mkdir();
  48. }
  49. }else{
  50. new AlertDialog.Builder(this).setMessage(“检测到手机没有存储卡!请插入手机存储卡再开启本应用。”)
  51. .setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
  52. @Override
  53. public void onClick(DialogInterface dialog, int which) {
  54. finish();
  55. }
  56. }).show();
  57. }
  58. }
  59. /**
  60. * 点击拍照按钮,启动拍照
  61. */
  62. private final OnClickListener TakePicListener = new OnClickListener(){
  63. @Override
  64. public void onClick(View v) {
  65. mCamera.autoFocus(new AutoFoucus()); //自动对焦
  66. }
  67. };
  68. /**
  69. * 自动对焦后拍照
  70. * @author aokunsang
  71. * @Date 2011-12-5
  72. */
  73. private final class AutoFoucus implements AutoFocusCallback{
  74. @Override
  75. public void onAutoFocus(boolean success, Camera camera) {
  76. if(success && mCamera!=null){
  77. mCamera.takePicture(mShutterCallback, null, mPictureCallback);
  78. }
  79. }
  80. }
  81. /**
  82. * 重点对象、 此处实例化了一个本界面的PictureCallback
  83. * 当用户拍完一张照片的时候触发,这时候对图片处理并保存操作。
  84. *
  85. */
  86. private final PictureCallback mPictureCallback = new PictureCallback() {
  87. @Override
  88. public void onPictureTaken(byte[] data, Camera camera) {
  89. try {
  90. String fileName = System.currentTimeMillis()+”.jpg”;
  91. File file = new File(imgPath,fileName);
  92. Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
  93. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
  94. bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
  95. bos.flush();
  96. bos.close();
  97. Intent intent = new Intent(TakePhotoAct.this,PictureViewAct.class);
  98. intent.putExtra(“imagePath”, file.getPath());
  99. startActivity(intent);
  100. } catch (Exception e) {
  101. e.printStackTrace();
  102. }
  103. }
  104. };
  105. /**
  106. * 在相机快门关闭时候的回调接口,通过这个接口来通知用户快门关闭的事件,
  107. * 普通相机在快门关闭的时候都会发出响声,根据需要可以在该回调接口中定义各种动作, 例如:使设备震动
  108. */
  109. private final ShutterCallback mShutterCallback = new ShutterCallback() {
  110. public void onShutter() {
  111. Log.d(“ShutterCallback”, “…onShutter…”);
  112. }
  113. };
  114. @Override
  115. /**
  116. * 初始化相机参数,比如相机的参数: 像素, 大小,格式
  117. */
  118. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  119. int height) {
  120. Camera.Parameters param = mCamera.getParameters();
  121. /**
  122. * 设置拍照图片格式
  123. */
  124. param.setPictureFormat(PixelFormat.JPEG);
  125. /**
  126. * 设置预览尺寸【这里需要注意:预览尺寸有些数字正确,有些会报错,不清楚为啥】
  127. */
  128. //param.setPreviewSize(320, 240);
  129. /**
  130. * 设置图片大小
  131. */
  132. param.setPictureSize(Const.width, Const.height);
  133. mCamera.setParameters(param);
  134. /**
  135. * 开始预览
  136. */
  137. mCamera.startPreview();
  138. }
  139. @Override
  140. /**
  141. * 打开相机,设置预览
  142. */
  143. public void surfaceCreated(SurfaceHolder holder) {
  144. try {
  145. mCamera = Camera.open(); //打开摄像头
  146. mCamera.setPreviewDisplay(holder);
  147. } catch (IOException e) {
  148. mCamera.release();
  149. mCamera = null;
  150. }
  151. }
  152. @Override
  153. /**
  154. * 预览界面被关闭时,或者停止相机拍摄;释放相机资源
  155. */
  156. public void surfaceDestroyed(SurfaceHolder holder) {
  157. mCamera.stopPreview();
  158. if(mCamera!=null) mCamera.release();
  159. mCamera = null;
  160. }
  161. @Override
  162. public boolean onKeyDown(int keyCode, KeyEvent event) {
  163. if(keyCode == KeyEvent.KEYCODE_CAMERA){ //按下相机实体按键,启动本程序照相功能
  164. mCamera.autoFocus(new AutoFoucus()); //自动对焦
  165. return true;
  166. }else{
  167. return false;
  168. }
  169. }

    xml:

Xml代码 收藏代码

  1. <?**xml version=”1.0” encoding=”utf-8”?>**
  2. <**LinearLayout** xmlns:android=”http://schemas.android.com/apk/res/android“
  3. android:orientation=”vertical”
  4. android:layout_width=”fill_parent”
  5. android:layout_height=”fill_parent”
  6. >
  7. <**SurfaceView**
  8. android:id=”@+id/surface_camera”
  9. android:layout_width=”fill_parent”
  10. android:layout_height=”fill_parent”
  11. android:layout_weight=”1”
  12. />
  13. <**LinearLayout**
  14. android:orientation=”horizontal”
  15. android:layout_width=”fill_parent”
  16. android:layout_height=”wrap_content”>
  17. <**Button**
  18. android:text=”拍照”
  19. android:layout_width=”wrap_content”
  20. android:layout_height=”wrap_content”
  21. android:id=”@+id/takepic”
  22. />
  23. <**Button**
  24. android:text=”退出”
  25. android:layout_width=”wrap_content”
  26. android:layout_height=”wrap_content”
  27. android:id=”@+id/exit”
  28. />
  29. </**LinearLayout**>
  30. </**LinearLayout**>

    预览功能:

    /**

Java代码 收藏代码

  1. * 图片预览
  2. * @author: aokunsang
  3. * @date: 2012-8-1
  4. */
  5. public class PictureScanAct extends Activity {
  6. private GridView gridView;
  7. private ImageAdapter imgAdapter;
  8. private List fileNameList = new ArrayList();
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.picturescan);
  13. gridView = (GridView)findViewById(R.id.picture_grid);
  14. imgAdapter = new ImageAdapter(this);
  15. gridView.setAdapter(imgAdapter);
  16. gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  17. @Override
  18. public void onItemClick(AdapterView<?> parent, View view,
  19. int position, long id) {
  20. String fileName = fileNameList.get(position);
  21. startActivity(new Intent(PictureScanAct.this, PictureViewAct.class).putExtra(“flag”,”upload”).putExtra(“imagePath”,fileName));
  22. }
  23. });
  24. //setProgressBarIndeterminateVisibility(true);
  25. Toast.makeText(this, “加载图片中….”, Toast.LENGTH_LONG).show();
  26. new AsyncLoadedImage().execute();
  27. }
  28. /**
  29. * 向适配器添加图片
  30. * @param bitmap
  31. */
  32. private void addImage(Bitmap… loadImages){
  33. for(Bitmap loadImage:loadImages){
  34. imgAdapter.addPhoto(loadImage);
  35. }
  36. }
  37. /**
  38. * 释放内存
  39. */
  40. protected void onDestroy() {
  41. super.onDestroy();
  42. final GridView grid = gridView;
  43. final int count = grid.getChildCount();
  44. ImageView v = null;
  45. for (int i = 0; i < count; i++) {
  46. v = (ImageView) grid.getChildAt(i);
  47. ((BitmapDrawable) v.getDrawable()).setCallback(null);
  48. }
  49. }
  50. /**
  51. * 异步加载图片展示
  52. * @author: aokunsang
  53. * @date: 2012-8-1
  54. */
  55. class AsyncLoadedImage extends AsyncTask {
  56. @Override
  57. protected Boolean doInBackground(Object… params) {
  58. File fileDir = new File(Const.imgPath);
  59. File[] files = fileDir.listFiles();
  60. boolean result = false;
  61. if(files!=null){
  62. for(File file:files){
  63. String fileName = file.getName();
  64. if (fileName.lastIndexOf(“.”) > 0
  65. && fileName.substring(fileName.lastIndexOf(“.”) + 1,
  66. fileName.length()).equals(“jpg”)){
  67. Bitmap bitmap;
  68. Bitmap newBitmap;
  69. try {
  70. BitmapFactory.Options options = new BitmapFactory.Options();
  71. options.inSampleSize = 10;
  72. bitmap = BitmapFactory.decodeFile(file.getPath(), options);
  73. newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 100, 100);
  74. bitmap.recycle();
  75. if (newBitmap != null) {
  76. fileNameList.add(file.getPath());
  77. publishProgress(newBitmap);
  78. result = true;
  79. }
  80. } catch (Exception e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }
  85. }
  86. return result;
  87. }
  88. @Override
  89. public void onProgressUpdate(Bitmap… value) {
  90. addImage(value);
  91. }
  92. @Override
  93. protected void onPostExecute(Boolean result) {
  94. if(!result){
  95. showDialog(1);
  96. }
  97. }
  98. }
  99. @Override
  100. protected Dialog onCreateDialog(int id) {
  101. AlertDialog dialog = new AlertDialog.Builder(PictureScanAct.this).setTitle(“温馨提示”).setMessage(“暂时还没有照片,请先采集照片!”)
  102. .setPositiveButton(“确定”, new DialogInterface.OnClickListener(){
  103. @Override
  104. public void onClick(DialogInterface dialog, int which) {
  105. startActivity(new Intent(PictureScanAct.this,TakePhotoAct.class));
  106. }
  107. }).setNegativeButton(“取消”, new DialogInterface.OnClickListener() {
  108. @Override
  109. public void onClick(DialogInterface dialog, int which) {
  110. finish();
  111. }
  112. }).show();
  113. return dialog;
  114. }
  115. }

GridView适配器:

  1. public class ImageAdapter extends BaseAdapter \{

Java代码 收藏代码

  1. private List picList = new ArrayList();
  2. private Context mContext;
  3. public ImageAdapter(Context mContext){
  4. this.mContext = mContext;
  5. }
  6. @Override
  7. public int getCount() {
  8. return picList.size();
  9. }
  10. /* (non-Javadoc)
  11. * @see android.widget.Adapter#getItem(int)
  12. */
  13. @Override
  14. public Object getItem(int position) {
  15. // TODO Auto-generated method stub
  16. return picList.get(position);
  17. }
  18. /**
  19. * 添加图片
  20. * @param bitmap
  21. */
  22. public void addPhoto(Bitmap loadImage){
  23. picList.add(loadImage);
  24. notifyDataSetChanged();
  25. }
  26. /* (non-Javadoc)
  27. * @see android.widget.Adapter#getItemId(int)
  28. */
  29. @Override
  30. public long getItemId(int position) {
  31. // TODO Auto-generated method stub
  32. return position;
  33. }
  34. @Override
  35. public View getView(int position, View convertView, ViewGroup parent) {
  36. ImageView imageView = null;
  37. if(convertView == null){
  38. imageView = new ImageView(mContext);
  39. imageView.setLayoutParams(new GridView.LayoutParams(110, 110));
  40. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
  41. imageView.setPadding(5,5,5,5);
  42. }else{
  43. imageView = (ImageView)convertView;
  44. }
  45. imageView.setImageBitmap(picList.get(position));
  46. return imageView;
  47. }

图片预览界面:

  1. <?xml version="1.0" encoding="utf-8"?>

Xml代码 收藏代码

  1. <**GridView** xmlns:android=”http://schemas.android.com/apk/res/android“
  2. android:id=”@+id/picture_grid”
  3. android:layout_width=”match_parent”
  4. android:layout_height=”match_parent”
  5. android:numColumns=”4”
  6. android:verticalSpacing=”5dip”
  7. android:horizontalSpacing=”5dip”
  8. android:stretchMode=”columnWidth”
  9. android:columnWidth=”120dip”
  10. android:gravity=”center”
  11. >
  12. </**GridView**>

预览图片:

f6625342-b987-3b0e-a73e-060c47e57a96.png
272fe655-5918-366a-aef1-f60837c3d7bc.png

上传工具类:

Java代码 收藏代码

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.Map;
  9. import java.util.Map.Entry;
  10. import android.util.Log;
  11. import com.peacemap.photo.po.FileInfo;
  12. /**
  13. * POST上传文件
  14. * @author aokunsang
  15. * @Date 2011-12-6
  16. */
  17. public class PostFile {
  18. private static PostFile postFile = new PostFile();
  19. private final static String LINEND = “\r\n”;
  20. private final static String BOUNDARY = “—————————————-7da2137580612”; //数据分隔线
  21. private final static String PREFIX = “—“;
  22. private final static String MUTIPART_FORMDATA = “multipart/form-data”;
  23. private final static String CHARSET = “utf-8”;
  24. private final static String CONTENTTYPE = “application/octet-stream”;
  25. private PostFile(){}
  26. public static PostFile getInstance(){
  27. return postFile;
  28. }
  29. /**
  30. * HTTP上传文件
  31. * @param actionUrl 请求服务器的路径
  32. * @param params 传递的表单内容
  33. * @param files 多个文件信息
  34. * @return
  35. */
  36. public String post(String actionUrl,Map params,FileInfo[] files){
  37. try {
  38. URL url = new URL(actionUrl);
  39. HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
  40. urlConn.setDoOutput(true); //允许输出
  41. urlConn.setDoInput(true); //允许输入
  42. urlConn.setUseCaches(false);
  43. urlConn.setRequestMethod(“POST”);
  44. urlConn.setRequestProperty(“connection”, “Keep-Alive”);
  45. urlConn.setRequestProperty(“Charset”, CHARSET);
  46. urlConn.setRequestProperty(“Content-Type”, MUTIPART_FORMDATA+”;boundary=”+BOUNDARY);
  47. DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
  48. //构建表单数据
  49. String entryText = bulidFormText(params);
  50. Log.i(“———-描述信息———————-“, entryText);
  51. dos.write(entryText.getBytes());
  52. StringBuffer sb = new StringBuffer(“”);
  53. for(FileInfo file : files){
  54. sb.append(PREFIX).append(BOUNDARY).append(LINEND);
  55. sb.append(“Content-Disposition: form-data; name=\“”+file.getFileTextName()+”\“; filename=\“”+file.getFile().getAbsolutePath()+”\“”+LINEND);
  56. sb.append(“Content-Type:”+CONTENTTYPE+”;charset=”+CHARSET+LINEND);
  57. sb.append(LINEND);
  58. dos.write(sb.toString().getBytes());
  59. InputStream is = new FileInputStream(file.getFile());
  60. byte[] buffer = new byte[1024];
  61. int len = 0;
  62. while ((len = is.read(buffer)) != -1) {
  63. dos.write(buffer, 0, len);
  64. }
  65. is.close();
  66. dos.write(LINEND.getBytes());
  67. }
  68. //请求的结束标志
  69. byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
  70. dos.write(end_data);
  71. dos.flush();
  72. //—————————————————- 发送请求数据结束 ——————————————
  73. //————————————————— 接收返回信息 ————————————
  74. int code = urlConn.getResponseCode();
  75. if(code!=200){
  76. urlConn.disconnect();
  77. return “”;
  78. }else{
  79. BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
  80. String result = “”;
  81. String line = null;
  82. while((line = br.readLine())!=null){
  83. result += line;
  84. }
  85. br.close();
  86. urlConn.disconnect();
  87. return result;
  88. }
  89. } catch (Exception e) {
  90. Log.e(“————上传图片错误————“, e.getMessage());
  91. return null;
  92. }
  93. }
  94. /**
  95. * HTTP上传单个文件
  96. * @param actionUrl 请求服务器的路径
  97. * @param params 传递的表单内容
  98. * @param files 单个文件信息
  99. * @return
  100. */
  101. public String post(String actionUrl,Map params,FileInfo fileInfo){
  102. return post(actionUrl, params, new FileInfo[]{fileInfo});
  103. }
  104. /**
  105. * 封装表单文本数据
  106. * @param paramText
  107. * @return
  108. */
  109. private String bulidFormText(Map paramText){
  110. if(paramText==null || paramText.isEmpty()) return “”;
  111. StringBuffer sb = new StringBuffer(“”);
  112. for(Entry entry : paramText.entrySet()){
  113. sb.append(PREFIX).append(BOUNDARY).append(LINEND);
  114. sb.append(“Content-Disposition:form-data;name=\“”
    • entry.getKey() + “\“” + LINEND);
  115. // sb.append(“Content-Type:text/plain;charset=” + CHARSET + LINEND);
  116. sb.append(LINEND);
  117. sb.append(entry.getValue());
  118. sb.append(LINEND);
  119. }
  120. return sb.toString();
  121. }
  122. /**
  123. * 封装文件文本数据
  124. * @param files
  125. * @return
  126. */
  127. private String buildFromFile(FileInfo[] files){
  128. StringBuffer sb = new StringBuffer();
  129. for(FileInfo file : files){
  130. sb.append(PREFIX).append(BOUNDARY).append(LINEND);
  131. sb.append(“Content-Disposition: form-data; name=\“”+file.getFileTextName()+”\“; filename=\“”+file.getFile().getAbsolutePath()+”\“”+LINEND);
  132. sb.append(“Content-Type:”+CONTENTTYPE+”;charset=”+CHARSET+LINEND);
  133. sb.append(LINEND);
  134. }
  135. return sb.toString();
  136. }
  137. }

    上传图片时对图片进行压缩处理(压缩处理程序):

    /**

Java代码 收藏代码

  1. * 压缩图片上传
  2. * @param picPath
  3. * @return
  4. */
  5. private synchronized File compressPicture(String picPath){
  6. int maxWidth = 640,maxHeight=480; //设置新图片的大小
  7. String fileName = picPath.substring(picPath.lastIndexOf(“/“));
  8. BitmapFactory.Options options = new BitmapFactory.Options();
  9. options.inJustDecodeBounds = true;
  10. Bitmap image = BitmapFactory.decodeFile(picPath, options);
  11. double ratio = 1D;
  12. if (maxWidth > 0 && maxHeight <= 0) {
  13. // 限定宽度,高度不做限制
  14. ratio = Math.ceil(options.outWidth / maxWidth);
  15. } else if (maxHeight > 0 && maxWidth <= 0) {
  16. // 限定高度,不限制宽度
  17. ratio = Math.ceil(options.outHeight / maxHeight);
  18. } else if (maxWidth > 0 && maxHeight > 0) {
  19. // 高度和宽度都做了限制,这时候我们计算在这个限制内能容纳的最大的图片尺寸,不会使图片变形
  20. double _widthRatio = Math.ceil(options.outWidth / maxWidth);
  21. double _heightRatio = (double) Math.ceil(options.outHeight / maxHeight);
  22. ratio = _widthRatio > _heightRatio ? _widthRatio : _heightRatio;
  23. }
  24. if (ratio > 1)
  25. options.inSampleSize = (int) ratio;
  26. options.inJustDecodeBounds = false;
  27. options.inPreferredConfig = Bitmap.Config.RGB_565;
  28. image = BitmapFactory.decodeFile(picPath, options);
  29. //保存入sdCard
  30. File file = new File(Const.thumbnailPath+fileName);
  31. try {
  32. FileOutputStream out = new FileOutputStream(file);
  33. if(image.compress(Bitmap.CompressFormat.JPEG, 100, out)){
  34. out.flush();
  35. out.close();
  36. }
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. return new File(picPath);
  40. }finally{
  41. if(image!=null && !image.isRecycled()){
  42. image.recycle();
  43. }
  44. }
  45. return file;
  46. }

-——————————————————我是个华丽的分割线,哇哈哈————————————- -————— -—————

做完这个拍照后,感觉功能太简单,比如:设置图片大小,白天夜晚照相等等一些系统照相机带的功能都没有,因此用在项目中感觉不炫。 然后就用了简单点的,直接调用系统照相机了。本来想着简单呢,后来也遇到点问题。

  1. (1)根据Camera Activity返回的时候,会带一个名为data Bitmap对象,照片的缩略图(这个地方可以做各种修改,我没用到不说了),上代码:

Java代码 收藏代码

  1. @Override
  2. public void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. checkSoftStage();
  5. try {
  6. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  7. startActivityForResult(intent, TAKE_PICTURE);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. /**
  13. * 检测手机是否存在SD卡,网络连接是否打开
  14. */
  15. private void checkSoftStage(){
  16. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //判断是否存在SD卡
  17. File file = new File(imgPath);
  18. if(!file.exists()){
  19. file.mkdir();
  20. }
  21. }else{
  22. new AlertDialog.Builder(this).setMessage(“检测到手机没有存储卡!请插入手机存储卡再开启本应用。”)
  23. .setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
  24. @Override
  25. public void onClick(DialogInterface dialog, int which) {
  26. finish();
  27. }
  28. }).show();
  29. }
  30. }
  31. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  32. if (resultCode == TAKE_PICTURE) {
  33. // 拍照Activity保存图像数据的key是data,返回的数据类型是Bitmap对象
  34. Bitmap cameraBitmap = (Bitmap) data.getExtras().get(“/sdcard/rtest.jpg”);
  35. // 在ImageView组件中显示拍摄的照片
  36. image.setImageBitmap(cameraBitmap);
  37. // 做自己的业务操作。。。。
  38. }
  39. super.onActivityResult(requestCode, resultCode, data);
  40. }
  1. (2) 以上代码在我的小米手机上测试时,出现问题了。 返回的namedataBitmap对象是个Null,我发现小米照完相片之后,他会先跳到一个预览的界面(系统自带的页面),所以得不到Bitmap对象了。

因此我就先保存照片以及其路径,然后在 onActivityResult中获取图片,做业务操作,代码如下:

Java代码 收藏代码

  1. public void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. checkSoftStage();
  4. try {
  5. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  6. startActivityForResult(intent, TAKE_PICTURE);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. try {
  11. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  12. String fileName = System.currentTimeMillis()+”.jpg”;
  13. newImgPath = imgPath + “/“ + fileName;
  14. Uri uri = Uri.fromFile(new File(imgPath,fileName));
  15. intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
  16. startActivityForResult(intent, TAKE_PICTURE);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. @Override
  22. protected void onActivityResult(int requestCode,
  23. int resultCode, Intent data) {
  24. Log.i(“————图片路径————-“, “———“+newImgPath+”————-“);
  25. //…..做一些业务操作
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. super.onActivityResult(requestCode, resultCode, data);
  30. }

发表评论

表情:
评论列表 (有 0 条评论,316人围观)

还没有评论,来说两句吧...

相关阅读

    相关 图片

    > 小编推荐:[Fundebug][]提供JS错误监控、微信小程序错误监控、微信小游戏错误监控,Node.j错误监控和Java错误监控。真的是一个很好用的错误监控费服务,众多大

    相关 一个图片

    一、一个按钮上传文件操作 前台选择文件,只能通过input的file类型的文件选择框操作。但有时却为了界面的美观,要求用按钮来完成。 第一步、隐藏文件选择框 第二步、