Android编程图片操作类定义与用法示例【拍照,相册选图及裁剪】

时间:2019-04-13
本文章向大家介绍Android编程图片操作类定义与用法示例【拍照,相册选图及裁剪】,主要包括Android编程图片操作类定义与用法示例【拍照,相册选图及裁剪】使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了Android编程图片操作类定义与用法。分享给大家供大家参考,具体如下:

主界面类:拍照及选择相册图片

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
/**
 * Android中图片操作(拍照,相册图片选择及图片裁剪)
 * 作者:ldm
 * 时间:20162016/7/11 09:09
 */
public class ImageTestActivity extends Activity implements View.OnClickListener {
  //拍照
  private Button take_photo;
  //从相册中选择图片
  private Button local_pic;
  //图片展示
  private ImageView upload_image;
  //定义操作常量
  private final static int TAKE_PHOTO_REQUEST = 1;
  private final static int LOCAL_PICS_REQUEST = 2;
  private final static int UPLOAD_PIC_REQUEST = 3;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_test);
    //初始化控件及监听事件
    initViews();
  }
  private void initViews() {
    this.upload_image = (ImageView) findViewById(R.id.upload_image);
    this.take_photo = (Button) findViewById(R.id.take_photo);
    this.local_pic = (Button) findViewById(R.id.local_pics);
    this.take_photo.setOnClickListener(this);
    this.local_pic.setOnClickListener(this);
  }
  @Override
  public void onClick(View view) {
    if (view.getId() == R.id.take_photo) {//拍照
      //调用系统拍照In
      Intent photoIn = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(photoIn, TAKE_PHOTO_REQUEST);
    } else if (view.getId() == R.id.local_pics) {//从相册选择
      Intent picsIn = new Intent(Intent.ACTION_GET_CONTENT);
      picsIn.setType("image/*");//设置选择的数据类型为图片类型
      startActivityForResult(picsIn, LOCAL_PICS_REQUEST);
    }
  }
  //拍照或选择相册后,数据在这里处理
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (null == data) {
      return;
    }
    switch (requestCode) {
      case TAKE_PHOTO_REQUEST:
        Bundle bundle = data.getExtras();//获取到图片数据
        if (null != bundle) {
          Bitmap bm = bundle.getParcelable("data");
          //把图片展示在ImView上
//          upload_image.setImageBitmap(bm);
          //对图片剪
          Uri uri = ImageUtils.saveBitmapToSdCard(bm);
          startImageCrop(uri);
        }
        break;
      case LOCAL_PICS_REQUEST:
        Uri uri = data.getData();//从图片的Uri是以cotent://格式开头的
        //获取到图片
        Bitmap bm = ImageUtils.uri2Bitmap(ImageTestActivity.this, uri);
        //把图片展示在ImView上
//        upload_image.setImageBitmap(bm);
        //把拍照的图片保存到本地并转换成文件格式的Uri
        Uri fileUri = ImageUtils.saveBitmapToSdCard(bm);
        //对图片剪
        startImageCrop(fileUri);
        break;
      case UPLOAD_PIC_REQUEST:
        //把裁剪后的图片展示出来
        Bundle b = data.getExtras();
        Bitmap bitmap = b.getParcelable("data");
        //图片展示出来
        upload_image.setImageBitmap(bitmap);
        break;
    }
  }
  /**
   * @param
   * @description 图片裁剪
   * @author ldm
   * @time 2016/7/11 10:07
   */
  private void startImageCrop(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");//设置Uri及类型
    intent.putExtra("crop", "true");//
    intent.putExtra("aspectX", 2);//X方向上的比例
    intent.putExtra("aspectY", 1);//Y方向上的比例
    intent.putExtra("outputX", 200);//裁剪区的X方向宽
    intent.putExtra("outputY", 100);//裁剪区的Y方向宽
    intent.putExtra("scale", true);//是否保留比例
    intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
    intent.putExtra("return-data", true);//是否将数据保留在Bitmap中返回dataParcelable相应的Bitmap数据
    startActivityForResult(intent, UPLOAD_PIC_REQUEST);
  }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <Button
    android:id="@+id/take_photo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:text="拍照上传" />
  <Button
    android:id="@+id/local_pics"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:text="本地图库上传" />
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="图片信息展示"
    android:layout_marginLeft="10dp"
    android:textSize="16sp"/>
  <ImageView
    android:id="@+id/upload_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"/>
</LinearLayout>

图片操作工具类

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.format.DateFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Locale;
/**
 * description:从图片中获取到的Uri是以content://开头的,从U中找到对应图片
 * 作者:ldm
 * 间:20162016/7/11 09:47
 */
public class ImageUtils {
  public static Bitmap uri2Bitmap(Context mContext, Uri uri) {
    InputStream in = null;
    try {
      in = mContext.getContentResolver().openInputStream(uri);
      //从输入流中获取到图片
      Bitmap bm = BitmapFactory.decodeStream(in);
      in.close();
      return bm;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * @param
   * @description 保存图片到手机SD卡, 并返回图片对应的文件i
   * @author ldm
   * @time 2016/7/11 9:55
   */
  public static Uri saveBitmapToSdCard(Bitmap bm) {
    //自定义图片名称
    String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".png";
    //定义图片存放的位置
    File tempFile = new File("/sdcard/Image/");
    if (!tempFile.exists()) {
      tempFile.mkdir();
    }
    String fileName = "/sdcard/Image/" + name;
    File pic = new File(fileName);
    try {
      FileOutputStream os = new FileOutputStream(pic);
      //对图片进行压缩
      bm.compress(Bitmap.CompressFormat.PNG, 100, os);
      os.flush();
      os.close();
      return Uri.fromFile(pic);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

最后不要忘记在AndroidManifest.xml中添加 相应权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

注:更多关于Android权限控制的说明可点击此处查看Android权限操作说明

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android图形与图像处理技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。