當前位置:首頁 » 安卓系統 » android拍照代碼

android拍照代碼

發布時間: 2022-09-07 23:03:24

❶ 如何調用android的拍照或本地相冊選取,然後再實現相片上傳伺服器

首先是拍照:使用Intent即可,

[java] view plainprint?
01.final String start = Environment.getExternalStorageState();
02.private static final String PHOTOPATH = "/photo/";
03.
04.if(start.equals(Environment.MEDIA_MOUNTED)){
05.Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
06.File file = new File(Environment.getExternalStorageDirectory()+PHOTOPATH);
07.if(!file.exists()){
08.file.mkdirs();
09.}
10.tempphontname = System.currentTimeMillis()+".jpg";
11.buffer.append(Environment.getExternalStorageDirectory()+PHOTOPATH).append(tempphontname);
12.intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(buffer.toString())));
13.startActivityForResult(intent, 1);
14.}
final String start = Environment.getExternalStorageState();
private static final String PHOTOPATH = "/photo/";

if(start.equals(Environment.MEDIA_MOUNTED)){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+PHOTOPATH);
if(!file.exists()){
file.mkdirs();
}
tempphontname = System.currentTimeMillis()+".jpg";
buffer.append(Environment.getExternalStorageDirectory()+PHOTOPATH).append(tempphontname);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(buffer.toString())));
startActivityForResult(intent, 1);
}
其次是從本地相冊選:依舊是Intent.

如下代碼:

[java] view plainprint?
01.if(start.equals(Environment.MEDIA_MOUNTED)){
02. Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
03. getImage.addCategory(Intent.CATEGORY_OPENABLE);
04. getImage.setType("image/jpeg");
05. startActivityForResult(getImage, 0);
06.}
if(start.equals(Environment.MEDIA_MOUNTED)){
Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
getImage.addCategory(Intent.CATEGORY_OPENABLE);
getImage.setType("image/jpeg");
startActivityForResult(getImage, 0);
}

接下來是主要的:因為調用完系統的方法後,回返回到回調方法onActivityResult(int, int, Intent)中,

在裡面進行主要的照片上傳伺服器的操作,

見代碼:

[java] view plainprint?
01.@Override
02. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
03. ContentResolver resolver = getContentResolver();
04. if(requestCode==1)//
05. {
06. if(resultCode==Activity.RESULT_OK)
07. {
08. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
09. {
10.ew Thread(new Runnable()
11. {
12. @Override
13. public void run() {
14.//進行上傳操作
15.}
16.}.start();
轉載

❷ Android WebView 調用系統拍照和相冊

由於業務需要,APP內嵌H5,需要調去系統相冊和拍照,網上找了點資料,整理一下,供大家參考:

private static final int REQUEST_CAMERA =1;

private static final int REQUEST_CHOOSE =2;

private ValueCallbackmUploadMessage;

private ;

private UricameraUri;

//5.0以後的方法

webView.setWebChromeClient(new WebChromeClient() {

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

@Override

    public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {

if (mUploadMessagesAboveL !=null) {

mUploadMessagesAboveL.onReceiveValue(null);

            mUploadMessagesAboveL =null;

        }else {

mUploadMessagesAboveL = filePathCallback;

            selectImage();

        }

return true;

    }

});

//選擇圖片和拍照,對應的string文件,可以自己寫死:拍照,相冊,取消

private void selectImage() {

ActionSheet.createBuilder(this, getSupportFragmentManager()).

setOtherButtonTitles(new String[]{getResources().getString(R.string.common_tip_photos), getResources().getString(R.string.common_picture)}).

setCancelButtonTitle(getResources().getString(R.string.common_cancel)).setCancelableOnTouchOutside(true).setListener(new ActionSheet.ActionSheetListener() {

public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

if (mUploadMessage !=null) {

mUploadMessage.onReceiveValue(null);

                mUploadMessage =null;

            }

if (mUploadMessagesAboveL !=null) {

mUploadMessagesAboveL.onReceiveValue(null);

                mUploadMessagesAboveL =null;

            }

actionSheet.dismiss();

        }

@RequiresApi(api = Build.VERSION_CODES.M)

public void onOtherButtonClick(ActionSheet actionSheet, int index) {

switch (index) {

case 0:

chosePicture();

break;

                case 1:

setRequestCamera();

            }

}

}).show();

}

//拍照,添加許可權申請  這個可以自己寫下,我這邊是項目中寫好的,直接拿過來用了

public void setRequestCamera() {

permissionsBuilder =new YXTPermissionsBuilder.Builder(this)

.setOnGrantedListener((requestCode, perms) -> {

openCamera();

            })

.setRationale4NeverAskAgain(LanguageUtils.isEnglish() ? String.format(getString(R.string.permission_tips), getString(R.string.common_camera), getString(R.string.app_name), getString(R.string.app_name)) :

String.format(getString(R.string.permission_tips), getString(R.string.app_name), getString(R.string.common_camera), getString(R.string.app_name)))

//必需

            .setRequestCode(ConstantsData.GET_CAMERA)

.build();

    permissionsBuilder.requestPermissions(Manifest.permission.CAMERA);

}

/**

* 本地相冊選擇圖片

*/

private void chosePicture() {

Intent innerIntent =new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    innerIntent.setType("image/*");

    Intent wrapperIntent = Intent.createChooser(innerIntent, null);

    startActivityForResult(wrapperIntent, REQUEST_CHOOSE);

}

/**

* 打開照相機

*/

private void openCamera() {

Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    String imagePaths = Environment.getExternalStorageDirectory().getPath() +"/pbccrc/Images/" + (System.currentTimeMillis() +".jpg");

    // 必須確保文件夾路徑存在,否則拍照後無法完成回調

    File vFile =new File(imagePaths);

    if (!vFile.exists()) {

File vDirPath = vFile.getParentFile();

        vDirPath.mkdirs();

    }else {

if (vFile.exists()) {

vFile.delete();

        }

}

cameraUri = FileProvider.getUriForFile(

this,

            getPackageName() +".fileprovider",

            vFile);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);

    startActivityForResult(intent, REQUEST_CAMERA);

}

/**

* 選擇照片後結束

*

* @param data

*/

private UriafterChosePic(Intent data) {

if (data !=null) {

final String path = data.getData().getPath();

        if (path !=null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {

return data.getData();

        }else {

Toast.makeText(this, "上傳的圖片僅支持png或jpg格式", Toast.LENGTH_SHORT).show();

        }

}

return null;

}

/**

* 返迴文件選擇

*/

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

if (mUploadMessagesAboveL !=null) {

onActivityResultAboveL(requestCode, resultCode, intent);

    }

if (mUploadMessage ==null)return;

    Uri uri =null;

    if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {

uri =cameraUri;

        Log.e("onActivityResult: " + uri.toString());

    }

if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {

uri = afterChosePic(intent);

    }

mUploadMessage.onReceiveValue(uri);

    mUploadMessage =null;

    super.onActivityResult(requestCode, resultCode, intent);

}

/**

* 5.0以後機型 返迴文件選擇

*

* @param requestCode

* @param resultCode

* @param data

*/

private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {

Uri[] results =null;

    if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {

results =new Uri[]{cameraUri};

    }

if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {

if (data !=null) {

String dataString = data.getDataString();

            if (dataString !=null)

results =new Uri[]{Uri.parse(dataString)};

        }

}

mUploadMessagesAboveL.onReceiveValue(results);

    mUploadMessagesAboveL =null;

return;

}

基本都可以拿去用了,希望有幫助

❸ android開發怎麼實現拍照上傳

這個其實是一個很泛的問題

我大致說下我的思路:

  1. 用startactivityforresult方法調用系統的攝像頭,隨便拍張照片,把照片保存在某一目錄下面

  2. 點擊完成後,會在onactivityresult中,根據目錄的地址,再把這目錄下面的資源得轉換為文件,接著通過介面進行提交。提交成功後,後台返回一個URL。

  3. 通過這個URL,運用imageload(第三方插件)顯示圖片

❹ 怎麼調用android的攝像頭拍照

我們要調用攝像頭的拍照功能,顯然
第一步必須加入調用攝像頭硬體的許可權,拍完照後我們要將圖片保存在SD卡中,必須加入SD卡讀寫許可權,所以第一步,我們應該在Android清單文件中加入以下代碼
<uses-permission android:name="android.permission.CAMERA"/>//攝像頭許可權
SD卡讀寫許可權
<uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
第二步,要將攝像頭捕獲的圖像實時地顯示在手機上。
我們是用SurfaceView這個視圖組件來實現的,因此在main.xml中加入下列代碼
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/surfaceview"
/>
第三步,設置窗口的顯示方式
首先獲得當前窗口Windowwindow = getWindow();//得到窗口
接著設置沒有標題requestWindowFeature(Window.FEATURE_NO_TITLE);//沒有標題
接著設置全屏 window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);//設置全屏
當然,我們在拍照過程中,屏幕必須一致處於高亮狀態,因此接著加入下面代碼
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//設置高亮
至此,我們將窗口的顯示方式規定死了,然後才能設置窗口上顯示的組件(順序非常重要)
setContentView(R.layout.main);
第四步,設置SurficeView顯示控制項的屬性
找到surficeView
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
設置它的像素為800x600
surfaceView.getHolder().setFixedSize(800,480);
//下面設置surfaceView不維護自己的緩沖區,而是等待屏幕的渲染引擎將內容推送到用戶面前
surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
第五步,就是為surficeView加入回調方法(callBack)
surfaceView.getHolder().addCallback(newSurfaceCallback());
上面的回調類是我們自己定義的,代碼如下
private class SurfaceCallback implementsSurfaceHolder.Callback{
@Override
public void surfaceCreated(SurfaceHolderholder) {
try {
camera = Camera.open();//打開硬體攝像頭,這里導包得時候一定要注意是android.hardware.Camera
WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);//得到窗口管理器
Display display = wm.getDefaultDisplay();//得到當前屏幕
Camera.Parameters parameters =camera.getParameters();//得到攝像頭的參數
parameters.setPreviewSize(display.getWidth(),display.getHeight());//設置預覽照片的大小
parameters.setPreviewFrameRate(3);//設置每秒3幀
parameters.setPictureFormat(PixelFormat.JPEG);//設置照片的格式
parameters.setJpegQuality(85);//設置照片的質量
parameters.setPictureSize(display.getHeight(),display.getWidth());//設置照片的大小,默認是和屏幕一樣大
camera.setParameters(parameters);
camera.setPreviewDisplay(surfaceView.getHolder());//通過SurfaceView顯示取景畫面
camera.startPreview();//開始預覽
isPreview = true;//設置是否預覽參數為真
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}

@Override
public void surfaceChanged(SurfaceHolderholder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolderholder) {
if(camera!=null){
if(isPreview){//如果正在預覽
camera.stopPreview();
camera.release();
}
}
}
}
第六步,我們必須對按鍵事件進行監聽,如是拍照還是聚焦,代碼如下
public boolean onKeyDown(int keyCode,KeyEvent event) {//處理按鍵事件
if(camera!=null&&event.getRepeatCount()==0)//代表只按了一下
{
switch(keyCode){
case KeyEvent.KEYCODE_BACK://如果是搜索鍵
camera.autoFocus(null);//自動對焦
break;
case KeyEvent.KEYCODE_DPAD_CENTER://如果是中間鍵
camera.takePicture(null, null, new TakePictureCallback());//將拍到的照片給第三個對象中,這里的TakePictureCallback()是自己定義的,在下面的代碼中
break;
}
}
return true;//阻止事件往下傳遞,否則按搜索鍵會變成系統默認的
}
------------------------------------------------------------------------------------------
private final class TakePictureCallbackimplements PictureCallback{
public void onPictureTaken(byte[] data,Camera camera) {
try {
Bitmap bitmap =BitmapFactory.decodeByteArray(data, 0, data.length);
File file = newFile(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
FileOutputStream outputStream = newFileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100,outputStream);
outputStream.close();
camera.stopPreview();
camera.startPreview();//處理完數據之後可以預覽
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
注意,代碼中有兩個回調類,一個是SurfaceCallback(),另外一個是TakePictureCallback(),初學者可能一時難以理解,通俗地講,前者是用來監視surficeView這個暫時存放圖片數據的顯示控制項的,根據它的顯示情況調用不同的方法,包括surfaceCreated(),surfaceChanged(),surfaceDestroyed(),也就不難理解為什麼會有這三個回調方法了(注意,在surfaceDestroyed()方法中必須釋放攝像頭,詳細代碼參見上方)。TakePictureCallback()是為了監視是否拍照而設計的介面,期中也僅有一個方法,camera將拍照得到的數據傳入方法,我們便可以對拍照得到的數據進行進一步處理

❺ 如何在android中後台開啟攝像頭默默拍照

(1)CameraActivity.java

package com.camera.test;import android.app.Activity;import android.content.pm.ActivityInfo;import android.os.Bundle;import android.view.Window;import android.view.WindowManager;import android.widget.RelativeLayout;public class CameraActivity extends Activity {private CameraView view;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);requestWindowFeature(Window.FEATURE_NO_TITLE);// 設置橫屏模式以及全屏模式view = new CameraView(this);// 通過一個surfaceview的view來實現拍照view.setId(1);view = new CameraView(this, this);setContentView(R.layout.camera_layout);RelativeLayout relative = (RelativeLayout) this.findViewById(R.id.ly);RelativeLayout.LayoutParams Layout = new RelativeLayout.LayoutParams(3, 3);// 設置surfaceview使其滿足需求無法觀看預覽Layout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);Layout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);relative.addView(view, Layout);}}(2) CameraView.javapackage com.camera.test;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Point;import android.graphics.PointF;import android.hardware.Camera;import android.hardware.Camera.AutoFocusCallback;import android.hardware.Camera.ShutterCallback;import android.media.AudioManager;import android.media.FaceDetector;import android.media.FaceDetector.Face;import android.os.Environment;import android.os.Handler;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.widget.Toast;public class CameraView extends SurfaceView implements SurfaceHolder.Callback,Camera.PictureCallback{private SurfaceHolder holder;private Camera camera;private Camera.Parameters parameters;private Activity act;private Handler handler = new Handler();private Context context;private SurfaceView surfaceView;private AudioManager audio;private int current;public CameraView(Context context) {super(context);surfaceView = this;audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);final int current = audio.getRingerMode();audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);this.context = context;holder = getHolder();// 生成Surface Holderholder.addCallback(this);holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// 指定Push Bufferhandler.postDelayed(new Runnable() {@Overridepublic void run() {if (camera == null) {handler.postDelayed(this, 1 * 1000);// 由於啟動camera需要時間,在此讓其等兩秒再進行聚焦知道camera不為空} else {camera.autoFocus(new AutoFocusCallback() {@Overridepublic void onAutoFocus(boolean success, Camera camera) {if (success) {camera.takePicture(new ShutterCallback() {// 如果聚焦成功則進行拍照@Overridepublic void onShutter() {}}, null, CameraView.this);} else {}}});}}}, 2 * 1000);}public CameraView(Context context, Activity act) {// 在此定義一個構造方法用於拍照過後把CameraActivity給finish掉this(context);this.act = act;}@Overridepublic void surfaceCreated(final SurfaceHolder holder) {// TODO Auto-generated method stubcamera = Camera.open();// 攝像頭的初始化handler.postDelayed(new Runnable() {@Overridepublic void run() {if (holder != null) {try {camera.setPreviewDisplay(holder);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {handler.postDelayed(this, 1 * 1000);}}}, 2 * 1000);}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {// TODO Auto-generated method stubparameters = camera.getParameters();camera.setParameters(parameters);// 設置參數camera.startPreview();// 開始預覽}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {// TODO Auto-generated method stub}public void onPictureTaken(byte[] data, Camera camera) {// 拍攝完成後保存照片try {Date date = new Date();SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");String time = format.format(date);//在SD卡上創建文件夾File file = new File(Environment.getExternalStorageDirectory()+ "/myCamera/pic");if (!file.exists()) {file.mkdirs();}String path = Environment.getExternalStorageDirectory()+ "/myCamera/pic/" + time + ".jpg";data2file(data, path);camera.setPreviewCallback(null);camera.stopPreview();camera.release();camera = null;holder.removeCallback(CameraView.this);audio.setRingerMode(current);act.finish();//uploadFile(path);} catch (Exception e) {}}private void data2file(byte[] w, String fileName) throws Exception {// 將二進制數據轉換為文件的函數FileOutputStream out = null;try {out = new FileOutputStream(fileName);out.write(w);out.close();} catch (Exception e) {if (out != null)out.close();throw e;}}// private void uploadFile(String filePath)// 拍照過後上傳文件到伺服器// {// }}

❻ Android 使用系統相機拍照和讀取相冊照片

1.拍照 (對於7.0以上的版本,不在允許直接訪問uri)
`

若不指定輸出路徑intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity)); 在onActivityResult()中,通過

`
可以拿到uri,但獲得的圖片是被壓縮過的。若指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);輸出路徑,則此處的intent為null,但可以使用我們存的uri讀取照片,此時的照片沒有被壓縮。

2.從相冊中讀取照片, 方法:
`

`
即使設置 intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity));輸出路徑,仍然不能從此路徑中讀取,只能在onActivityForResult()中通過event.uri = intent.getData();方式獲得圖片uri。
此種現象也好理解,拍照時產生新的圖片,自然可根據設置的uri進行圖片保存,而讀取相冊時,圖片已經在目錄中不能轉移到自己設定的uri中。

Androidmanifest.xml中
`

在 res/xml/provider_paths.xml
`

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="JDTobs" path=""/>
<files-path name="name" path="path" />
<cache-path name="name" path="path" /> <external-path name="name" path="path" />
<external-files-path name="name" path="path" />
<external-cache-path name="name" path="path" /> </paths> `

讀取uri

❼ 怎麼用程序實現調用Android手機的拍照功能

public class testActivity extends Activity {

public static final int NONE = 0;
public static final int PHOTOHRAPH = 1;// 拍照
public static final int PHOTOZOOM = 2; // 縮放
public static final int PHOTORESOULT = 3;// 結果

public static final String IMAGE_UNSPECIFIED = "image/*";
ImageView imageView = null;
Button button0 = null;
Button button1 = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageID);
button0 = (Button) findViewById(R.id.btn_01);
button1 = (Button) findViewById(R.id.btn_02);

button0.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
startActivityForResult(intent, PHOTOZOOM);
}
});

button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
startActivityForResult(intent, PHOTOHRAPH);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == NONE)
return;
// 拍照
if (requestCode == PHOTOHRAPH) {
//設置文件保存路徑這里放在跟目錄下
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
startPhotoZoom(Uri.fromFile(picture));
}

if (data == null)
return;

// 讀取相冊縮放圖片
if (requestCode == PHOTOZOOM) {
startPhotoZoom(data.getData());
}
// 處理結果
if (requestCode == PHOTORESOULT) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)壓縮文件
imageView.setImageBitmap(photo);
}

}

super.onActivityResult(requestCode, resultCode, data);
}

public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", 64);
intent.putExtra("outputY", 64);
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTORESOULT);
}
}

❽ android 用AlertDialog啟用相機許可權的代碼怎麼寫啊

/**
* @Description 調用系統相機照相,獲取原圖像
* @param activity 就是你的mainactivity
* @param dir 拍照後保存在本地的圖片路徑
* @param filename 圖片的名稱
* @param cmd 返回的requestCode

* @return void
*/
public static boolean takePhoto(final Activity activity, final String dir,
final String filename, final int cmd) {
String filePath = dir + filename;

// final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Log.d("test", "MediaStore.ACTION_IMAGE_CAPTURE"
+ android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE == null ? "android.media.action.IMAGE_CAPTURE"
: android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final File cameraDir = new File(dir);
if (!cameraDir.exists()) {
// return false;
cameraDir.mkdirs();
}

final File file = new File(filePath);
final Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
try {
activity.startActivityForResult(intent, cmd);

} catch (final ActivityNotFoundException e) {
return false;
}
return true;
}

然後在你的onactivityforresult方法里寫:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {
case PHOTOGRAPH://拍照
if (resultCode == RESULT_OK) {
String url = FileHelper.Get_SDCardPath() + Constant.HHXH_IMGDIR
+ BitmapUtil.tempPhoto;//圖片路徑,和你前面調用相冊時設的路徑一樣
Bitmap bitmap = BitmapUtil
.extractThumbNail(url, 480, 320, true);//這里是根據本地路徑獲取圖片並壓縮的,這個我寫的代碼比較多就不上傳了
findviewbyid(R.id.imgPhoto).setImageBitmap(bitmap);

}
}
}

熱點內容
編程式控制制小船 發布:2025-01-11 05:35:05 瀏覽:756
螢石雲清理緩存 發布:2025-01-11 05:34:29 瀏覽:779
怎麼在電腦上傳照片 發布:2025-01-11 05:30:20 瀏覽:487
python3哪個版本好 發布:2025-01-11 05:07:29 瀏覽:864
手機怎麼訪問外網 發布:2025-01-11 05:07:27 瀏覽:532
財務信息伺服器搭建 發布:2025-01-11 04:48:09 瀏覽:875
演算法實現過程 發布:2025-01-11 04:43:45 瀏覽:457
瞄準下載ftp 發布:2025-01-11 04:43:44 瀏覽:573
校園電影腳本 發布:2025-01-11 04:32:08 瀏覽:437
現在手機配置最高是什麼 發布:2025-01-11 04:30:37 瀏覽:549