zoukankan      html  css  js  c++  java
  • 调用系统相机、相册、视频

    调用系统相机

    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v7.app.AppCompatActivity;
    import android.text.format.DateFormat;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Calendar;
    import java.util.Locale;
    
    public class MainActivity extends AppCompatActivity {
    
        private Button button;
        private ImageView view;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button = (Button) findViewById(R.id.button);
            view= (ImageView)findViewById(R.id.image);
            button.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 1);
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == Activity.RESULT_OK) {
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }
                new DateFormat();
                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                Toast.makeText(this, name, Toast.LENGTH_LONG).show();
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
    
                FileOutputStream b = null;
                File file = new File("/sdcard/Image/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/Image/"+name;
    
                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try
                {
                    view.setImageBitmap(bitmap);// 将图片显示在ImageView里
                }catch(Exception e)
                {
                    Log.e("error", e.getMessage());
                }
    
            }
        }
    }
    <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="de.hdodenhof.picture.MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击选择图片" />
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="250dp"
            android:layout_height="250dp" />
    </LinearLayout>
    <!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    调用系统相册

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.ImageView;
    
    public class MainActivity extends AppCompatActivity {
    
        //调用系统相册-选择图片
        private static final int IMAGE = 1;
    
        //所需权限
    //    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onClick(View v) {
            //调用相册
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, IMAGE);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //获取图片路径
            if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                String imagePath = c.getString(columnIndex);
                showImage(imagePath);
                c.close();
            }
        }
    
        //加载图片
        private void showImage(String imaePath) {
            Bitmap bm = BitmapUtils.getBitmap(imaePath, 400, 400);
    //        Bitmap bm = BitmapFactory.decodeFile(imaePath);
            ((ImageView) findViewById(R.id.image)).setImageBitmap(bm);
        }
    }
    <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="de.hdodenhof.photo.MainActivity">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="点击选择图片" />
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="250dp"
            android:layout_height="250dp" />
    
    </LinearLayout>

    选择系统相册还是相机工具类

    需求:点击修改头像,弹出对话框提示选择相册还是相机,从而调用系统相册或相机

    值得注意的是:从照片拍摄图像时,系统会默认压缩的很小,导致显示的图片失真;解决办法:得到拍摄的原图,保存,然后手动压缩到需要的尺寸,再显示

    <!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    import android.graphics.Bitmap;
    
    /**
     * Created by Administrator on 2016/10/17.
     */
    public class GetPhotoEntity {
    
        private Bitmap bitmap;
        private String imgUrl;
    
        public Bitmap getBitmap() {
            return bitmap;
        }
    
        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }
    
        public String getImgUrl() {
            return imgUrl;
        }
    
        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }
    }
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.text.format.DateFormat;
    import android.view.View;
    
    import com.xuehu365.xuehu.model.Constant;
    import com.xuehu365.xuehu.model.GetPhotoEntity;
    import com.xuehu365.xuehu.ui.widget.AlertDialog;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Calendar;
    import java.util.Locale;
    
    /**
     * Created by Administrator on 2016/10/15.
     */
    public class GetPhotoUtils {
    
        //相片来源类型
        public static String touxiangType;
        public static String imageName;
    
        /**
         * 弹出选择相片来源对话框
         */
        public static void showDialog(final Context context) {
            AlertDialog alertDialog = new AlertDialog(context).builder();
            alertDialog.setTitle("选择相片来源").setPositiveButton("相册", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //调用相册
                    touxiangType = Constant.picture;
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    
                    ((Activity) context).startActivityForResult(intent, Constant.IMAGE);
                }
            }).setNegativeButton("去照相", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //调用照相机
                    touxiangType = Constant.photo;
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    imageName = getPhotopath();
                    File file = new File("/sdcard/Image/");
                    file.mkdirs();
                    String fileName = "/sdcard/Image/" + imageName;
                    LogHelp.i("image", "printIn:" + fileName);
                    File out = new File(fileName);
                    Uri uri = Uri.fromFile(out);
                    // 获取拍照后未压缩的原图片,并保存在uri路径中
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    ((Activity) context).startActivityForResult(intent, Constant.IMAGE);
                }
            }).show();
        }
    
        /**
         * 获取原图片名称
         *
         * @return
         */
        public static String getPhotopath() {
            new DateFormat();
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            return name;
        }
    
        /**
         * 回调加载图片
         */
        public static GetPhotoEntity setBitmap(int resultCode, Intent data, Context context) {
            GetPhotoEntity entity = new GetPhotoEntity();
            //判断是来自相册还是相机
            if (touxiangType.equals(Constant.photo)) {
                if (resultCode == Activity.RESULT_OK) {
                    String sdStatus = Environment.getExternalStorageState();
                    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                        return null;
                    }
    //                Bundle bundle = data.getExtras();
    //                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
                    FileOutputStream b = null;
                    File file = new File("/sdcard/Image/");
                    file.mkdirs();// 创建文件夹
                    String fileName = "/sdcard/Image/" + imageName;
                    LogHelp.i("image", "printOut:" + fileName);
                    Bitmap bitmap = BitmapUtils.getBitmap(fileName, 1280, 720);
                    try {
                        b = new FileOutputStream(fileName);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            b.flush();
                            b.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    entity.setBitmap(bitmap);
                    entity.setImgUrl(fileName);
                    return entity;
                }
            } else if (touxiangType.equals(Constant.picture)) {
                //获取图片路径
                if (/*requestCode == Constant.IMAGE && */resultCode == Activity.RESULT_OK/* && data != null*/) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = context.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String imagePath = c.getString(columnIndex);
                    Bitmap bitmap = BitmapUtils.getBitmap(imagePath, 240, 240);
                    c.close();
                    entity.setBitmap(bitmap);
                    entity.setImgUrl(imagePath);
                    return entity;
                }
            }
            return null;
        }
    }

    调用系统视频

    private void chooseVideo() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        //intent.setType("image/*");
        // intent.setType("audio/*"); //选择音频
    //        intent.setType("video/*"); //选择视频 (mp4 3gp 是android支持的视频格式)
    
         intent.setType("video/*;image/*");//同时选择视频和图片
    
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
    }
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // 选取图片的返回值  
        if (requestCode == 1) {  
            //  
            if (resultCode == RESULT_OK) {  
                Uri uri = data.getData();  
                Cursor cursor = getContentResolver().query(uri, null, null,  
                        null, null);  
                cursor.moveToFirst();  
                // String imgNo = cursor.getString(0); // 图片编号  
                String v_path = cursor.getString(1); // 图片文件路径  
                String v_size = cursor.getString(2); // 图片大小  
                String v_name = cursor.getString(3); // 图片文件名  
                LogUtil.e("v_path="+v_path);  
                LogUtil.e("v_size="+v_size);  
                LogUtil.e("v_name="+v_name);  
            }  
        }  
        super.onActivityResult(requestCode, resultCode, data);  
    }  
    //拿到视频第一帧
    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    mmr.setDataSource(videoPath);
    Bitmap bitmap = mmr.getFrameAtTime();
    video_layout.setImageBitmap(bitmap);
  • 相关阅读:
    使用top观察一进程的cpu历史占用情况
    djangoForm组件
    djangoAdmin组件
    js-metisMenu
    css-bootstrap
    flask环境安装
    python数据结构转换&格式化
    linux安装odbc for mysql
    json模块
    urllib模块
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5965201.html
Copyright © 2011-2022 走看看