Android 拍照和从本地获取图片

2 篇文章 0 订阅
1 篇文章 0 订阅


项目地址 https://github.com/16ren/Androidgetphoto.git



MainActivity.java
package com.example.androidgetphoto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private int REQUEST_CAMERA = 3621;
	private int SELECT_FILE = 6523;
	private Button bt_getphoto;
	private ImageView iv_main_test;
	private String mCurrentPhotoPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		bt_getphoto = (Button) (findViewById(R.id.bt_getphoto));
		iv_main_test = (ImageView) findViewById(R.id.iv_main_test);
		bt_getphoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getphoto();
			}
		});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {

			if (requestCode == REQUEST_CAMERA) {
				setPic();
				galleryAddPic();

			} else if (requestCode == SELECT_FILE) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				// Get the cursor
				Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
				// Move to first row
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				mCurrentPhotoPath = cursor.getString(columnIndex);
				cursor.close();
				setPic();

			}

		}
	}

	private void setPic() {
		// Get the dimensions of the View
		int targetW = iv_main_test.getWidth();
		int targetH = iv_main_test.getHeight();

		// Get the dimensions of the bitmap
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;

		// Determine how much to scale down the image
		int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

		// Decode the image file into a Bitmap sized to fill the View
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		iv_main_test.setImageBitmap(bitmap);
	}

	private void getphoto() {
		final String[] items = { "Gallery", "Camera", "Cancel" };
		Builder builder = new Builder(this);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				if (items[item].equals("Camera")) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					if (intent.resolveActivity(getPackageManager()) != null) {
						try {
							File f = createImageFile();
							// if you set MediaStore.EXTRA_OUTPUT the intent
							// maybe null in some div
							// set the postion that image save
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
							startActivityForResult(intent, REQUEST_CAMERA);
						} catch (IOException e) {
							e.printStackTrace();
						}

					}
				} else if (items[item].equals("Gallery")) {
					Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					intent.setType("image/*");
					startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
				} else if (items[item].equals("Cancel")) {
					dialog.dismiss();
				}
			}
		});
		builder.show();
	}

	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = "JPEG_" + timeStamp + "_";
		File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File image = File.createTempFile(imageFileName, /* prefix */
				".jpg", /* suffix */
				storageDir /* directory */
		);
		// Save a file: path for use with ACTION_VIEW intents
		mCurrentPhotoPath = image.getAbsolutePath();
		return image;
	}

	// Add the Photo to a Gallery
	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(mCurrentPhotoPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		this.sendBroadcast(mediaScanIntent);
	}
}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidgetphoto"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboard|keyboardHidden|screenSize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


mctivity_main.xml
<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.androidgetphoto.MainActivity" >

    <Button
        android:id="@+id/bt_getphoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="@string/getphoto" />

    <ImageView
        android:id="@+id/iv_main_test"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>


string.xml

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

    <string name="app_name">Androidgetphoto</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="getphoto">get photo</string>

</resources>

使用中的问题和解决方案
1.权限.

  保存拍照的图片到本地

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用
拍照功能

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

2.拍照图片返回形式
(1)直接返回

不指定图片保存位置 ,直接Bitmap bp =(Bitmap) data.getData()。这种形式获取到的只是一个拍照的缩略图,对于一搬的头像够用。

(2)先保存再读取

使用 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));指定拍照后图片保存的位置,这时要在activity中维护一个路径全局变量(private String mCurrentPhotoPath;);

这种情况可以获取一个没有压缩的图片,这种方式有些机型适配的问题,有些手机拍照成功,有些手机拍完照后确定返回后mCurrentPhotoPath数据为空,被销毁了。

经过代码查找发现,当这些出问题的手机被调用系统手机拍照时,当前activity被销毁了之后又被重新创建了。即Acitivity 执行了ondestory()-->onCreate(),所以Activity被重新创建了从而内部的数据丢失,而按照正常的逻辑该Activity应该入后台堆栈。一开始以为是系统启用照相机内存不够自动销毁回收。可有些手机不会出现该问题。之后经过本人细心研究activity的生命周期才恍然大悟,原来当手机横竖屏时系统会重新创建一个activity,这就是为什么上个activity会ondestory()-->onCreate()。但为什么有些手机会执行有些不会呢。问题就出在横竖屏上。因为有些手机的系统照相机弄的很炫会自动旋转90度,从而导致了横竖屏的发生(--!看来最潮的也不是好东西,苦了我们这些碼农)。这就是为什有些手机会发生有些不会。跟系统照相机是否旋转有关系。

解决方案   在AndroidManifest.xml加上 android:configChanges="orientation|keyboard|keyboardHidden|screenSize"  MainActivity.java 重载onConfigurationChanged(Configuration newConfig)

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboard|keyboardHidden|screenSize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO什么也不做
super.onConfigurationChanged(newConfig);}

(3)讲拍照后的图片添加到画廊,当然不添加也可以,只不过你手机自带的相册就里面不会显示你刚才拍摄的图片

	// Add the Photo to a Gallery
	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(mCurrentPhotoPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		this.sendBroadcast(mediaScanIntent);
	}

(4)内存不足的问题

对于一些手机拍照获取高清的图片,直接进行加载显示有时会内存不足,从而程序崩溃。

解决方式可以参照 http://blog.csdn.net/yudajun/article/details/9323941

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在安卓上拍照并保存到本地相册,你可以按照以下步骤进行操作: 1. 首先,在布局文件(activity_camera_demo.xml)中添加一个TextureView来显示相机预览界面,并添加一个拍照按钮(Button)。\[3\] 2. 在相应的Activity中,你需要获取相机权限,并初始化相机。你可以使用Camera2 API或者CameraX来实现相机功能。 3. 当用户点击拍照按钮时,你需要执行以下操作: - 创建一个文件来保存照片。你可以使用File类来创建一个新的文件,并指定保存路径和文件名。 - 设置相机的拍照参数,包括保存路径和文件格式等。 - 调用相机的拍照方法,将照片保存到指定的文件中。 4. 在拍照完成后,你可以通过MediaScannerConnection将照片添加到系统相册中,这样用户就可以在相册中查看到拍摄的照片。 需要注意的是,由于不同的安卓手机厂商对系统相册进行了不同程度的定制,所以在一些手机上,照片可能无法直接显示在相册最前方,而是需要在二级文件夹内查找。\[2\] 希望以上步骤对你有所帮助! #### 引用[.reference_title] - *1* [Android开发 拍照+读取相册+保存到本地](https://blog.csdn.net/zsprb1/article/details/128923756)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [调用系统相机拍照,并且保存到系统相册的一般套路](https://blog.csdn.net/weixin_39796752/article/details/117667427)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Android 实现拍照功能,并将图片保存到本地存储](https://blog.csdn.net/lu202032/article/details/122220467)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值