Android開發之呼叫攝像頭拍照
現在很多應用中都會要求使用者上傳一張圖片來作為頭像,首先我在這接收使用相機拍照和在相簿中選擇圖片。接下來先上效果圖:
接下來看程式碼:
1,佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.gyq.cameraalbumtest.MainActivity">
<Button
android:id="@+id/btn_take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="take photo"/>
<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="choose from album"/>
<ImageView
android:id="@+id/iv_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
2,MainActivity.java邏輯程式碼:
package com.gyq.cameraalbumtest;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private Button mTakePhoto, mChoosePhoto;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.btn_take_photo);
mChoosePhoto = (Button) findViewById(R.id.choose_from_album);
picture = (ImageView) findViewById(R.id.iv_picture);
mTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//建立file物件,用於儲存拍照後的圖片;
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
imageUri = FileProvider.getUriForFile(MainActivity.this,
"com.gyq.cameraalbumtest.fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
//啟動相機程式
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
mChoosePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}
//開啟相簿
private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bm);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) { //4.4及以上的系統使用這個方法處理圖片;
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data); //4.4及以下的系統使用這個方法處理圖片
}
}
default:
break;
}
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
private String getImagePath(Uri uri, String selection) {
String path = null;
//通過Uri和selection來獲取真實的圖片路徑
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
/**
* 4.4及以上的系統使用這個方法處理圖片
*
* @param data
*/
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
//如果document型別的Uri,則通過document來處理
String docID = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docID.split(":")[1]; //解析出數字格式的id
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content型別的uri,則使用普通方式使用
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是file型別的uri,直接獲取路徑即可
imagePath = uri.getPath();
}
displayImage(imagePath);
}
}
3,清單檔案:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gyq.cameraalbumtest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="com.gyq.cameraalbumtest.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
</manifest>
4,xml資料夾中的檔案
<?xml version = "1.0" encoding = "utf-8"?>
<paths xmlns:android = "http://schemas.android.com/apk/res/android">
<external-path name = "my_images" path = ""></external-path>
</paths>
OK,完成收工。請繼續關注我的部落格。謝謝!
相關文章
- Android呼叫攝像頭拍照Android
- 照片系列之android呼叫攝像頭拍照Android
- Android呼叫攝像頭拍照並顯示照片Android
- 安卓呼叫攝像頭拍照安卓
- Android提供的攝像頭拍照Android
- 安卓開發之呼叫攝像頭安卓
- 在Android中呼叫攝像頭拍照並顯示出來Android
- android studio呼叫攝像頭拍照及具體步驟演示程式碼Android
- 瀏覽器呼叫攝像頭進行拍照程式瀏覽器
- 【Android】【opencv】實現攝像頭拍照和錄影AndroidOpenCV
- android 開啟攝像頭Android
- web呼叫攝像頭拍照並上傳到伺服器Web伺服器
- UVC攝像頭按鍵拍照功能
- Android中呼叫攝像頭拍照儲存,並在相簿中選擇圖片顯示Android
- android studio之簡單呼叫攝像頭並且獲取其照片Android
- 純JavaScript實現的呼叫裝置攝像頭並拍照的功能JavaScript
- jQuery webcam plugin呼叫攝像頭jQueryWebPlugin
- android opencv 前置攝像頭AndroidOpenCV
- Android CameraX 開啟攝像頭預覽Android
- html5呼叫攝像頭功能HTML
- 教你如何利用python呼叫攝像頭Python
- HTML5如何呼叫攝像頭?HTML
- html5中呼叫攝像頭拍照並上傳(附繞過https的想法)HTMLHTTP
- html5呼叫攝像頭截圖HTML
- [譯]Android的多攝像頭支援Android
- [譯] Android 的多攝像頭支援Android
- iPhone XS/iPhone XS Max攝像頭拍照解析:蘋果也玩起了AI拍照iPhone蘋果AI
- Android 圓形頭像 相簿和拍照裁剪選取Android
- Android 攝像頭預覽懸浮窗Android
- [譯] 如何在 Android 開發中充分利用多攝像頭 APIAndroidAPI
- python版opencv:如何用筆記本攝像頭拍照儲存PythonOpenCV筆記
- WebRTC開啟本地攝像頭Web
- Android開發,《第一行程式碼(第三版)》呼叫攝像頭崩潰解決方法Android行程
- Win10攝像頭如何開啟_WIN10攝像頭在哪裡Win10
- matlab呼叫攝像頭並儲存成幀的形式Matlab
- Jetson AGX Xavier ROS下呼叫USB單目攝像頭ROS
- Android使用者請注意,你的相機正在偷偷開啟並拍照攝像Android
- 筆記本攝像頭怎麼開啟 筆記本設定攝像頭教程筆記
- AndroidCamera2拍照(三)——切換攝像頭,延時拍攝和閃光模式Android模式