图片相关--相册选择、拍照、缩放、裁减

来源:互联网 发布:sdrsharp软件下载 编辑:程序博客网 时间:2024/05/29 02:57

前言:现在的项目用到拍照,相册选择图片的功能,本以为这么炫的功能,应该难度很大吧。真是应了那句话,一件事,在没有尝试过,千万不要下结论!!!真的是万万没想到,android在调用系统功能方面做的如此优秀,了了几行代码,就完成了如何强大的功能。下面与大家分享代码;

看效果先:

从相册选择的功能:

                     指定宽度,按比例缩放                                                     指定宽高度               

  

拍照对应的功能:

                        裁剪(指定裁剪大小)                                              保存裁剪后的图像

   

一、XML

XML比较简单:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:background="#ffffff"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <ImageView  
  9.         android:id="@+id/imageID"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:adjustViewBounds="true"/>  
  13.   
  14.     <Button  
  15.         android:id="@+id/btn_01"  
  16.         android:layout_width="150dip"  
  17.         android:layout_height="50dip"  
  18.         android:text="相册" />  
  19.   
  20.     <Button  
  21.         android:id="@+id/btn_02"  
  22.         android:layout_width="150dip"  
  23.         android:layout_height="50dip"  
  24.         android:text="拍照" />  
  25.   
  26. </LinearLayout>  

二、JAVA代码

先贴是全部代码,然后逐个讲

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.iduona;  
  2. /** 
  3.  *@author harvic 
  4.  *@date 2014-1-16  
  5.  */  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.File;  
  8. import java.io.InputStream;  
  9.   
  10. import android.app.Activity;  
  11. import android.content.ContentResolver;  
  12. import android.content.Intent;  
  13. import android.graphics.Bitmap;  
  14. import android.graphics.BitmapFactory;  
  15. import android.graphics.Canvas;  
  16. import android.graphics.Matrix;  
  17. import android.graphics.PixelFormat;  
  18. import android.graphics.drawable.BitmapDrawable;  
  19. import android.graphics.drawable.Drawable;  
  20. import android.net.Uri;  
  21. import android.os.Bundle;  
  22. import android.os.Environment;  
  23. import android.provider.MediaStore;  
  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. public class PhotoActivity extends Activity {  
  31.   
  32.     public static final int NONE = 0;  
  33.     public static final int PHOTOHRAPH = 1;// 拍照  
  34.     public static final int PHOTOZOOM = 2// 缩放  
  35.     public static final int PHOTORESOULT = 3;// 结果  
  36.   
  37.     public static final String IMAGE_UNSPECIFIED = "image/*";  
  38.     ImageView imageView = null;  
  39.     Button button0 = null;  
  40.     Button button1 = null;  
  41.   
  42.     @Override  
  43.     public void onCreate(Bundle savedInstanceState) {  
  44.         super.onCreate(savedInstanceState);  
  45.         setContentView(R.layout.main);  
  46.         imageView = (ImageView) findViewById(R.id.imageID);  
  47.         button0 = (Button) findViewById(R.id.btn_01);  
  48.         button1 = (Button) findViewById(R.id.btn_02);  
  49.   
  50.         // 相册  
  51.         button0.setOnClickListener(new OnClickListener() {  
  52.   
  53.             public void onClick(View v) {  
  54.                 Intent intent = new Intent();  
  55.                 intent.setAction(Intent.ACTION_PICK);  
  56.   
  57.                 intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
  58.                 startActivityForResult(intent, PHOTOZOOM);  
  59.             }  
  60.         });  
  61.   
  62.         // 拍照  
  63.         button1.setOnClickListener(new OnClickListener() {  
  64.   
  65.             public void onClick(View v) {  
  66.                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  67.                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(  
  68.                         Environment.getExternalStorageDirectory(), "temp.jpg")));  
  69.                 System.out.println("============="  
  70.                         + Environment.getExternalStorageDirectory());  
  71.                 startActivityForResult(intent, PHOTOHRAPH);  
  72.             }  
  73.         });  
  74.     }  
  75.   
  76.     @Override  
  77.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  78.         ContentResolver resolver = getContentResolver();  
  79.   
  80.         if (resultCode == NONE||data == null)  
  81.             return;  
  82.   
  83.         // 拍照  
  84.         if (requestCode == PHOTOHRAPH) {  
  85.             // 设置文件保存路径这里放在跟目录下  
  86.             File picture = new File(Environment.getExternalStorageDirectory()  
  87.                     + "/temp.jpg");  
  88.             System.out.println("------------------------" + picture.getPath());  
  89.             startPhotoZoom(Uri.fromFile(picture));  
  90.         }  
  91.   
  92.         // 读取相册缩放图片  
  93.         if (requestCode == PHOTOZOOM) {  
  94.             try {  
  95.                 // 获得图片的uri  
  96.                 Uri originalUri = data.getData();  
  97.                 // 将图片内容解析成字节数组  
  98.                 byte[] mContent = readStream(resolver.openInputStream(Uri  
  99.                         .parse(originalUri.toString())));  
  100.                 // 将字节数组转换为BitmapDrawable对象  
  101.                 Bitmap myBitmap = getPicFromBytes(mContent, null);  
  102.                 BitmapDrawable bd = new BitmapDrawable(myBitmap);  
  103.                 //按比例缩放图片     
  104. //              Drawable d = zoomDrawable(bd, 150, 10, true);  
  105.                 //不按比例缩放图片,指定大小  
  106.                 Drawable d = zoomDrawable(bd, 150100false);  
  107.                 // //把得到的图片绑定在控件上显示  
  108.                 imageView.setImageDrawable(d);  
  109.             } catch (Exception e) {  
  110.                 System.out.println(e.getMessage());  
  111.             }  
  112.         }  
  113.         // 处理结果  
  114.         if (requestCode == PHOTORESOULT) {  
  115.             Bundle extras = data.getExtras();  
  116.             if (extras != null) {  
  117.                 Bitmap photo = extras.getParcelable("data");  
  118.                 ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  119.   
  120.                 photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -  
  121.                                                                         // 100)压缩文件  
  122.                 imageView.setImageBitmap(photo);  
  123.             }  
  124.   
  125.         }  
  126.   
  127.         super.onActivityResult(requestCode, resultCode, data);  
  128.     }  
  129.   
  130.     /**  
  131.      * 开启一个系统页面来裁剪传进来的照片  
  132.      *   
  133.      * @param Uri  
  134.      *            uri 需要裁剪的照片的URI值  
  135.      */  
  136.     public void startPhotoZoom(Uri uri) {  
  137.         Intent intent = new Intent("com.android.camera.action.CROP");  
  138.         intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
  139.         intent.putExtra("crop""true");  
  140.         // aspectX aspectY 是宽高的比例  
  141.         intent.putExtra("aspectX"1);  
  142.         intent.putExtra("aspectY"1);  
  143.         // outputX outputY 是裁剪图片宽高  
  144.         intent.putExtra("outputX"64);  
  145.         intent.putExtra("outputY"64);  
  146.         intent.putExtra("return-data"true);  
  147.         startActivityForResult(intent, PHOTORESOULT);  
  148.     }  
  149.   
  150.     /** 
  151.      * 将图片缩小/放大到指定宽高度 
  152.      *  
  153.      * @param Drawable 
  154.      *            drawable 图片的drawable 
  155.      * @param int w 指定缩小到的宽度 
  156.      * @param int h 指定缩小到的高度 
  157.      * @param Boolean 
  158.      *            scale 是否保持宽高比,TRUE:将忽略h的值,根据指定宽度自动计算高度 FALSE:根据指定宽度,高度生成图像 
  159.      * @return Drawable 返回新生成图片的Drawable 
  160.      */  
  161.   
  162.     private Drawable zoomDrawable(Drawable drawable, int w, int h, Boolean scale) {  
  163.         int width = drawable.getIntrinsicWidth();  
  164.         int height = drawable.getIntrinsicHeight();  
  165.         Bitmap oldbmp = drawableToBitmap(drawable);  
  166.         Matrix matrix = new Matrix();  
  167.         float scaleWidth;  
  168.         float scaleHeight;  
  169.         if (scale == true) {  
  170.             // 如果要保持宽高比,那说明高度跟宽度的缩放比例都是相同的  
  171.             scaleWidth = ((float) w / width);  
  172.             scaleHeight = ((float) w / width);  
  173.         } else {  
  174.             // 如果不保持缩放比,那就根据指定的宽高度进行缩放  
  175.             scaleWidth = ((float) w / width);  
  176.             scaleHeight = ((float) h / height);  
  177.         }  
  178.         matrix.postScale(scaleWidth, scaleHeight);  
  179.         Bitmap newbmp = Bitmap.createBitmap(oldbmp, 00, width, height,  
  180.                 matrix, true);  
  181.         return new BitmapDrawable(null, newbmp);  
  182.     }  
  183.   
  184.     /** 
  185.      * 根据图片Drawable返回图像 
  186.      *  
  187.      * @param drawable 
  188.      * @return Bitmap bitmap or null ;如果出错,返回NULL 
  189.      */  
  190.     private Bitmap drawableToBitmap(Drawable drawable) {  
  191.         Bitmap bitmap = null;  
  192.         try {  
  193.             int width = drawable.getIntrinsicWidth();  
  194.             int height = drawable.getIntrinsicHeight();  
  195.             Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
  196.                     : Bitmap.Config.RGB_565;  
  197.             bitmap = Bitmap.createBitmap(width, height, config);  
  198.             Canvas canvas = new Canvas(bitmap);  
  199.             drawable.setBounds(00, width, height);  
  200.             drawable.draw(canvas);  
  201.         } catch (Exception e) {  
  202.             // TODO: handle exception  
  203.             Toast.makeText(getApplicationContext(), "error:" + e.getMessage(),  
  204.                     Toast.LENGTH_SHORT).show();  
  205.         }  
  206.   
  207.         return bitmap;  
  208.     }  
  209.   
  210.     public static byte[] readStream(InputStream inStream) throws Exception {  
  211.         byte[] buffer = new byte[1024];  
  212.         int len = -1;  
  213.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  214.         while ((len = inStream.read(buffer)) != -1) {  
  215.             outStream.write(buffer, 0, len);  
  216.         }  
  217.         byte[] data = outStream.toByteArray();  
  218.         outStream.close();  
  219.         inStream.close();  
  220.         return data;  
  221.   
  222.     }  
  223.   
  224.     public static Bitmap getPicFromBytes(byte[] bytes,  
  225.             BitmapFactory.Options opts) {  
  226.         if (bytes != null)  
  227.             if (opts != null)  
  228.                 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,  
  229.                         opts);  
  230.             else  
  231.                 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
  232.         return null;  
  233.     }  
  234.   
  235. }  

1、先看OnCreate()函数里的代码,这段代码就是实现了点击按钮调用系统功能从相册里读照片还有拍照的功能的;

读取相册

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // 相册  
  2. button0.setOnClickListener(new OnClickListener() {  
  3.   
  4.     public void onClick(View v) {  
  5.         Intent intent = new Intent();  
  6.         intent.setAction(Intent.ACTION_PICK);  
  7.   
  8.         intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
  9.         startActivityForResult(intent, PHOTOZOOM);  
  10.     }  
  11. });  
这段代码实现转到相册里,然后返回时,发送结果码“2”,也就是定义的(PHOTOZOOM),以使当前Activity识别出是从这个命令返回的结果;

下面再看拍照功能:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // 拍照  
  2. button1.setOnClickListener(new OnClickListener() {  
  3.   
  4.     public void onClick(View v) {  
  5.         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  6.         intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(  
  7.                 Environment.getExternalStorageDirectory(), "temp.jpg")));  
  8.         System.out.println("============="  
  9.                     + Environment.getExternalStorageDirectory());  
  10.             startActivityForResult(intent, PHOTOHRAPH);  
  11.         }  
  12.     });  
  13. }  
相同调用startActivityForResult()在启动此系统调用的Activity后,在调用完毕返回结果到当前页面时,返回结果码“1”,对应PHOTOHRAPH,以便当前页面知道是从这个按钮的调用返回的结果;
2、返回结果操作代码

我们上面说了,调用startActivityForResult()传进去标识符,然后在调用结束后,返回结果和标识符到当前Activity,那当前页面怎么接收这些东东呢,这就需要重写onActivityResult()函数了,下面看提取的代码:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  2.     ContentResolver resolver = getContentResolver();  
  3.   
  4.     if (resultCode == NONE||data == null)  
  5.         return;  
  6.   
  7.     // 拍照  
  8.     if (requestCode == PHOTOHRAPH) {  
  9.         // 设置文件保存路径这里放在跟目录下  
  10.         File picture = new File(Environment.getExternalStorageDirectory()  
  11.                 + "/temp.jpg");  
  12.         System.out.println("------------------------" + picture.getPath());  
  13.         startPhotoZoom(Uri.fromFile(picture));  
  14.     }  
  15.   
  16.     // 读取相册缩放图片  
  17.     if (requestCode == PHOTOZOOM) {  
  18.         try {  
  19.             // 获得图片的uri  
  20.             Uri originalUri = data.getData();  
  21.             // 将图片内容解析成字节数组  
  22.             byte[] mContent = readStream(resolver.openInputStream(Uri  
  23.                     .parse(originalUri.toString())));  
  24.             // 将字节数组转换为BitmapDrawable对象  
  25.             Bitmap myBitmap = getPicFromBytes(mContent, null);  
  26.             BitmapDrawable bd = new BitmapDrawable(myBitmap);  
  27.             //按比例缩放图片     
  28. //              Drawable d = zoomDrawable(bd, 150, 10, true);  
  29.             //不按比例缩放图片,指定大小  
  30.             Drawable d = zoomDrawable(bd, 150100false);  
  31.             // //把得到的图片绑定在控件上显示  
  32.             imageView.setImageDrawable(d);  
  33.         } catch (Exception e) {  
  34.             System.out.println(e.getMessage());  
  35.         }  
  36.     }  
  37.     // 处理结果  
  38.     if (requestCode == PHOTORESOULT) {  
  39.         Bundle extras = data.getExtras();  
  40.         if (extras != null) {  
  41.             Bitmap photo = extras.getParcelable("data");  
  42.             ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  43.   
  44.             photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -  
  45.                                                                     // 100)压缩文件  
  46.             imageView.setImageBitmap(photo);  
  47.         }  
  48.   
  49.     }  
  50.   
  51.     super.onActivityResult(requestCode, resultCode, data);  
  52. }  
这里呢,就是根据不同的标识符判断是哪个调用返回的结果,然后根据不同的标识符,编写不同的代码;
看一个吧“拍照”:对应操作代码:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // 拍照  
  2. if (requestCode == PHOTOHRAPH) {  
  3.     // 设置文件保存路径这里放在跟目录下  
  4.     File picture = new File(Environment.getExternalStorageDirectory()  
  5.             + "/temp.jpg");  
  6.     System.out.println("------------------------" + picture.getPath());  
  7.     startPhotoZoom(Uri.fromFile(picture));  
  8. }  
其中startPhotoZoom()是自已写的,功能是跳转到裁剪页面
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void startPhotoZoom(Uri uri) {  
  2.     Intent intent = new Intent("com.android.camera.action.CROP");  
  3.     intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
  4.     intent.putExtra("crop""true");  
  5.     // aspectX aspectY 是宽高的比例  
  6.     intent.putExtra("aspectX"1);  
  7.     intent.putExtra("aspectY"1);  
  8.     // outputX outputY 是裁剪图片宽高  
  9.     intent.putExtra("outputX"64);  
  10.     intent.putExtra("outputY"64);  
  11.     intent.putExtra("return-data"true);  
  12.     startActivityForResult(intent, PHOTORESOULT);  
  13. }  
然后返回结果给当前Activity,然后标识位为:3  对应 PHOTORESOULT

同样,看onActivityResult()里的代码,同样对requestCode == PHOTORESOULT进行了处理,代码如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // 处理结果  
  2. if (requestCode == PHOTORESOULT) {  
  3.     Bundle extras = data.getExtras();  
  4.     if (extras != null) {  
  5.         Bitmap photo = extras.getParcelable("data");  
  6.         ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  7.   
  8.         photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -  
  9.                                                                 // 100)压缩文件  
  10.         imageView.setImageBitmap(photo);  
  11.     }  
  12.   
  13. }  
将返回在图片设置到imageView中;

对于,缩放图片的代码,我就不再细说了,下面这几个函数实现了这个功能:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 将图片缩小/放大到指定宽高度 
  3.  *  
  4.  * @param Drawable 
  5.  *            drawable 图片的drawable 
  6.  * @param int w 指定缩小到的宽度 
  7.  * @param int h 指定缩小到的高度 
  8.  * @param Boolean 
  9.  *            scale 是否保持宽高比,TRUE:将忽略h的值,根据指定宽度自动计算高度 FALSE:根据指定宽度,高度生成图像 
  10.  * @return Drawable 返回新生成图片的Drawable 
  11.  */  
  12.   
  13. private Drawable zoomDrawable(Drawable drawable, int w, int h, Boolean scale) {  
  14.     int width = drawable.getIntrinsicWidth();  
  15.     int height = drawable.getIntrinsicHeight();  
  16.     Bitmap oldbmp = drawableToBitmap(drawable);  
  17.     Matrix matrix = new Matrix();  
  18.     float scaleWidth;  
  19.     float scaleHeight;  
  20.     if (scale == true) {  
  21.         // 如果要保持宽高比,那说明高度跟宽度的缩放比例都是相同的  
  22.         scaleWidth = ((float) w / width);  
  23.         scaleHeight = ((float) w / width);  
  24.     } else {  
  25.         // 如果不保持缩放比,那就根据指定的宽高度进行缩放  
  26.         scaleWidth = ((float) w / width);  
  27.         scaleHeight = ((float) h / height);  
  28.     }  
  29.     matrix.postScale(scaleWidth, scaleHeight);  
  30.     Bitmap newbmp = Bitmap.createBitmap(oldbmp, 00, width, height,  
  31.             matrix, true);  
  32.     return new BitmapDrawable(null, newbmp);  
  33. }  
  34.   
  35. /** 
  36.  * 根据图片Drawable返回图像 
  37.  *  
  38.  * @param drawable 
  39.  * @return Bitmap bitmap or null ;如果出错,返回NULL 
  40.  */  
  41. private Bitmap drawableToBitmap(Drawable drawable) {  
  42.     Bitmap bitmap = null;  
  43.     try {  
  44.         int width = drawable.getIntrinsicWidth();  
  45.         int height = drawable.getIntrinsicHeight();  
  46.         Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
  47.                 : Bitmap.Config.RGB_565;  
  48.         bitmap = Bitmap.createBitmap(width, height, config);  
  49.         Canvas canvas = new Canvas(bitmap);  
  50.         drawable.setBounds(00, width, height);  
  51.         drawable.draw(canvas);  
  52.     } catch (Exception e) {  
  53.         // TODO: handle exception  
  54.         Toast.makeText(getApplicationContext(), "error:" + e.getMessage(),  
  55.                 Toast.LENGTH_SHORT).show();  
  56.     }  
  57.   
  58.     return bitmap;  
  59. }  
  60.   
  61. public static byte[] readStream(InputStream inStream) throws Exception {  
  62.     byte[] buffer = new byte[1024];  
  63.     int len = -1;  
  64.     ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  65.     while ((len = inStream.read(buffer)) != -1) {  
  66.         outStream.write(buffer, 0, len);  
  67.     }  
  68.     byte[] data = outStream.toByteArray();  
  69.     outStream.close();  
  70.     inStream.close();  
  71.     return data;  
  72.   
  73. }  
  74.   
  75. public static Bitmap getPicFromBytes(byte[] bytes,  
  76.         BitmapFactory.Options opts) {  
  77.     if (bytes != null)  
  78.         if (opts != null)  
  79.             return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,  
  80.                     opts);  
  81.         else  
  82.             return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
  83.     return null;  
  84. }  

源码来啦:http://download.csdn.net/detail/harvic880925/6855229(不要分,仅供分享)


请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/18353545  谢谢!!

0 0
原创粉丝点击