从相册或拍照获取图片,并实现图片的裁剪

MainActivity:

package com.example.xushuailong.mydopicture;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xushuailong.mydopicture.utils.Utilty;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_CAPTURE_CAMERA = 1;
    private static final int REQUEST_CODE_REL_CAPTURE_CAMERA = 2;
    private static final int REQUEST_CODE_CROP_CAPTURE_CAMERA = 3;
//    private static final int REQUEST_CODE_CROP_PICK_IMAGE = 3;
    private Button btn_get_from_album, btn_get_from_camera, btn_get_rel_from_camera, btn_get_crop_from_camera, btn_get_crop_from_album;
    private String ima_path;
    private TextView txt_img_path;
    private ImageView img;
    private String rel_ima_path;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE){
            //相册
            if (null != data) {
                Uri uri = data.getData();
                Log.d("xsl", "image_uri:" + uri);
                String img_path = Utilty.getPathFromKitKat(getApplicationContext(), uri);
                todoImageWithPatn(img_path);
            }
        }else if (requestCode == REQUEST_CODE_CAPTURE_CAMERA) {
            //相机
            if (null != data) {
                Uri uri = data.getData();
                Log.d("xsl", "camera_uri:" + uri);
                if (uri == null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        Bitmap photo = (Bitmap) bundle.get("data");
                        saveImage(photo, ima_path);
                    } else {
                        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //TODO do find the path of pic by uri
                }
            }
        }else if (requestCode == REQUEST_CODE_REL_CAPTURE_CAMERA){
            if (null != data){
                Log.d("xsl", "data_extra: " + data.getExtras());
            }else {
                Log.d("xsl", "data is null !");
            }
            todoImageWithPatn(rel_ima_path);
        }else if (requestCode == REQUEST_CODE_CROP_CAPTURE_CAMERA) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(Uri.fromFile(new File(rel_ima_path)), "image/*");
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(rel_ima_path)));
            startActivityForResult(intent, REQUEST_CODE_REL_CAPTURE_CAMERA);
        }
    }

    private void todoImageWithPatn(String ima_path) {
        txt_img_path.setText("path: " + ima_path);
//        img.setImageDrawable(Drawable.createFromPath(ima_path));
        try {
            img.setImageDrawable(Drawable.createFromStream(new FileInputStream(ima_path),System.currentTimeMillis()+"ss.jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveImage(Bitmap photo, String ima_path) {
//        img.setImageBitmap(photo);
        File file = new File(ima_path);
        if (!file.exists()){
            file.mkdirs();
        }
        BufferedOutputStream out = null;
        try {
            file = new File(ima_path + File.separator + System.currentTimeMillis() +".jpg");
            file.createNewFile();
            out = new BufferedOutputStream(new FileOutputStream(file.getPath(),false));
            Log.d("xsl","image_path: "+file.getPath());
            photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            todoImageWithPatn(file.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        viewEvents();
    }

    private void initViews() {
        btn_get_crop_from_album = (Button) findViewById(R.id.btn_get_crop_from_album);
        btn_get_crop_from_camera = (Button) findViewById(R.id.btn_get_crop_from_camera);
        btn_get_from_album = (Button) findViewById(R.id.btn_get_from_album);
        btn_get_from_camera = (Button) findViewById(R.id.btn_get_from_camera);
        btn_get_rel_from_camera = (Button) findViewById(R.id.btn_get_rel_from_camera);
        txt_img_path = (TextView) findViewById(R.id.txt_img_path);
        img = (ImageView) findViewById(R.id.img);
    }

    private void viewEvents() {
        btn_get_crop_from_album.setOnClickListener(this);
        btn_get_crop_from_camera.setOnClickListener(this);
        btn_get_from_album.setOnClickListener(this);
        btn_get_from_camera.setOnClickListener(this);
        btn_get_rel_from_camera.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_get_from_album:{
                getImageFromAlbum();
                break;
            }
            case R.id.btn_get_from_camera:{
                getImageFromCamera();
                break;
            }
            case R.id.btn_get_rel_from_camera:{
                getRelImageFromCamera();
                break;
            }
            case R.id.btn_get_crop_from_camera:{
                getCropImageFromCamera();
                break;
            }
            case R.id.btn_get_crop_from_album:{
                getCropImageFromAlbum();
                break;
            }
        }
    }

    public void getImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    public void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
            ima_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/";
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(intent,REQUEST_CODE_CAPTURE_CAMERA);
        }else {
            Toast.makeText(getApplicationContext(),"请确认已插入SD卡",Toast.LENGTH_SHORT).show();
        }
    }

    public void getRelImageFromCamera(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/rel_image";
            File dir = new File(out_file_path);
            if (!dir.exists()){
                dir.mkdirs();
            }
            rel_ima_path = out_file_path + File.separator + System.currentTimeMillis() + ".jpg";
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(rel_ima_path)));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, REQUEST_CODE_REL_CAPTURE_CAMERA);
        }
    }


    public void getCropImageFromCamera() {
        String out_img_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/crop_image";
        File dir = new File(out_img_path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        rel_ima_path = out_img_path + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rel_ima_path)));
        startActivityForResult(intent,REQUEST_CODE_CROP_CAPTURE_CAMERA);
    }

    public void getCropImageFromAlbum() {
        String out_img_path = Environment.getExternalStorageDirectory().getPath() + "/imge_temp/crop_chose";
        File dir = new File(out_img_path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        rel_ima_path = out_img_path + File.separator + System.currentTimeMillis() + ".jpg";
//        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        intent.putExtra("crop", true);
//        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rel_ima_path)));
        startActivityForResult(intent,REQUEST_CODE_REL_CAPTURE_CAMERA);
    }
}


utils:

package com.example.xushuailong.mydopicture.utils;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;


@TargetApi(Build.VERSION_CODES.KITKAT)
public class Utilty {

	/**
	 * 在android4.4上获取资源的路径
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getPathFromKitKat(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public static String getDataColumn(Context context, Uri uri,
			String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}


}

activity_layout::

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xushuailong.mydopicture.MainActivity">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/btn_get_from_album"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get pic from album"/>
        <Button
            android:id="@+id/btn_get_crop_from_album"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get crop pic from album"/>
        <Button
            android:id="@+id/btn_get_from_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get pic from camera"/>
         <Button
            android:id="@+id/btn_get_rel_from_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get rel pic from camera"/>
       <Button
            android:id="@+id/btn_get_crop_from_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get crop pic from camera"/>
        <TextView
            android:text="img_path: "
            android:maxLines="2"
            android:id="@+id/txt_img_path"
            android:layout_width="match_parent"
            android:layout_height="48dp" />
        <ImageView
            android:src="@mipmap/ic_launcher"
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitCenter"/>
    </LinearLayout>

</RelativeLayout>

这部分程序功能的bug是,当从相册选择的图片或拍照的图片太大的时候,ImageView就显示不出来图片,有待于进一步的优化。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现拍照裁剪图片功能需要以下步骤: 1. 添加权限 在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` 2. 创建布局文件 创建一个布局文件camera_preview.xml,并添加一个SurfaceView和一个Button,用于显示和拍照。 ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/camera_preview" android:layout_width="match_parent" android:layout_height="match_parent"> <SurfaceView android:id="@+id/surface_view" android:layout_width="match_parent" android:layout_height="match_parent"/> <Button android:id="@+id/button_capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="拍照" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 3. 实现拍照功能 在Activity中,获取Camera实例,并在SurfaceView上显示预览图像。当用户点击拍照按钮时,调用Camera.takePicture()方法拍照拍照成功后,保存照片并显示裁剪界面。 ```java public class CameraActivity extends Activity implements SurfaceHolder.Callback { private Camera mCamera; private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private Button mButtonCapture; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera_preview); // 获取SurfaceView和Button实例 mSurfaceView = findViewById(R.id.surface_view); mButtonCapture = findViewById(R.id.button_capture); // 监听Button点击事件 mButtonCapture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 拍照 mCamera.takePicture(null, null, mPictureCallback); } }); // 获取SurfaceHolder实例,并添加回调监听 mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder holder) { // 打开摄像头并设置预览 mCamera = Camera.open(); try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d("CameraTest", "Error setting camera preview: " + e.getMessage()); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 在SurfaceView上显示预览图像 if (mSurfaceHolder.getSurface() == null) { return; } try { mCamera.stopPreview(); } catch (Exception e) { Log.d("CameraTest", "Error stopping camera preview: " + e.getMessage()); } try { mCamera.setPreviewDisplay(mSurfaceHolder); mCamera.startPreview(); } catch (Exception e) { Log.d("CameraTest", "Error starting camera preview: " + e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // 释放摄像头资源 mCamera.stopPreview(); mCamera.release(); mCamera = null; } private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // 保存照片 File pictureFile = getOutputMediaFile(); if (pictureFile == null) { Log.d("CameraTest", "Error creating media file, check storage permissions"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d("CameraTest", "File not found: " + e.getMessage()); } catch (IOException e) { Log.d("CameraTest", "Error accessing file: " + e.getMessage()); } // 显示裁剪界面 Intent intent = new Intent(CameraActivity.this, CropActivity.class); intent.putExtra("image_path", pictureFile.getPath()); startActivity(intent); } }; private File getOutputMediaFile() { // 创建目录 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("CameraTest", "failed to create directory"); return null; } } // 创建文件 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; } } ``` 4. 实现裁剪功能 创建一个布局文件crop.xml,添加一个ImageView和一个Button,用于显示图片和保存裁剪后的图片。 ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/crop_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitCenter"/> <Button android:id="@+id/button_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 在CropActivity中,获取传递过来的图片路径,并将图片显示在ImageView上。当用户点击保存按钮时,调用Bitmap.createBitmap()方法裁剪图片,并保存到相册。 ```java public class CropActivity extends Activity { private ImageView mImageView; private Button mButtonSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.crop); // 获取ImageView和Button实例 mImageView = findViewById(R.id.image_view); mButtonSave = findViewById(R.id.button_save); // 获取传递过来的图片路径 Intent intent = getIntent(); String imagePath = intent.getStringExtra("image_path"); // 将图片显示在ImageView上 Bitmap bitmap = BitmapFactory.decodeFile(imagePath); mImageView.setImageBitmap(bitmap); // 监听Button点击事件 mButtonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 裁剪并保存图片 Bitmap croppedBitmap = getCroppedBitmap(bitmap); saveBitmapToGallery(croppedBitmap); Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show(); finish(); } }); } private Bitmap getCroppedBitmap(Bitmap bitmap) { // 获取ImageView的尺寸 int viewWidth = mImageView.getWidth(); int viewHeight = mImageView.getHeight(); // 获取图片的尺寸 int imageWidth = bitmap.getWidth(); int imageHeight = bitmap.getHeight(); // 计算缩放比例 float scale = Math.min((float) viewWidth / imageWidth, (float) viewHeight / imageHeight); // 计算裁剪区域 int cropWidth = (int) (viewWidth / scale); int cropHeight = (int) (viewHeight / scale); int x = (imageWidth - cropWidth) / 2; int y = (imageHeight - cropHeight) / 2; // 裁剪图片 Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, x, y, cropWidth, cropHeight); return croppedBitmap; } private void saveBitmapToGallery(Bitmap bitmap) { // 创建目录 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("CameraTest", "failed to create directory"); return; } } // 保存图片 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imagePath = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"; File imageFile = new File(imagePath); try { FileOutputStream fos = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (IOException e) { Log.d("CameraTest", "Error accessing file: " + e.getMessage()); } // 通知相册更新 MediaScannerConnection.scanFile(this, new String[]{imagePath}, null, null); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值