Android开发(15) 调用摄像头拍照,保存在照片到数据库

概述

有时候我们需要操作摄像头进行拍照,并保存照片。


拍照

  1. 启动摄像头
         //向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一个数据,那么返回标识ID。
        //在完成拍照后,新的照片会以此处的photoUri命名. 其实就是指定了个文件名
        ContentValues values = new ContentValues();
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //准备intent,并 指定 新 照片 的文件名(photoUri)
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
        //启动拍照的窗体。并注册 回调处理。
        startActivityForResult(intent, REQUEST_CODE_camera);
  1. 处理 回调。就是当拍照完成后,我们如何处理它。我们必须在activity的onActivityResult(要重载此方法)方法里处理它。

public void HandleonActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CameraHelper.REQUEST_CODE_camera) {

            ContentResolver cr = mContext.getContentResolver();
            if (photoUri == null)
                return;
            //按 刚刚指定 的那个文件名,查询数据库,获得更多的 照片信息,比如 图片的物理绝对路径
            Cursor cursor = cr.query(photoUri, null, null, null, null);
            if (cursor != null) {
                if (cursor.moveToNext()) {
                    String path = cursor.getString(1);
                    //获得图片
                    Bitmap bp = getBitMapFromPath(path);
                    imageView1.setImageBitmap(bp);

                    //写入到数据库
                    mBlobDAL.InsertImg(bp);
                }
                cursor.close();
            }
            photoUri = null;
        }
  1. 我们在这里需要处理图片的缩放。以为图片太大了,直接放入ImageView是无法显示的。
    /* 获得图片,并进行适当的 缩放。 图片太大的话,是无法展示的。 */
     private Bitmap getBitMapFromPath(String imageFilePath) {

        Display currentDisplay = getWindowManager().getDefaultDisplay();
        int dw = currentDisplay.getWidth();
        int dh = currentDisplay.getHeight();
        // Load up the image's dimensions not the image itself
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
                bmpFactoryOptions);
        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
                / (float) dh);
        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
                / (float) dw);

        // If both of the ratios are greater than 1,
        // one of the sides of the image is greater than the screen
        if (heightRatio > 1 && widthRatio > 1) {
            if (heightRatio > widthRatio) {
                // Height ratio is larger, scale according to it
                bmpFactoryOptions.inSampleSize = heightRatio;
            } else {
                // Width ratio is larger, scale according to it
                bmpFactoryOptions.inSampleSize = widthRatio;
            }
        }
        // Decode it for real
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
        return bmp;
    }

好了。处理摄像头拍照是完了。下面我们要把图片存放在数据里。

存储

  1. 建表
       @Override  
         publicvoid onCreate(SQLiteDatabase db) {

        String str = "CREATE TABLE [IMGS] ( [IDPK] integer PRIMARY KEY autoincrement,IMG_DATA blob )";
        db.execSQL(str);
    }
  1. 插入数据库。

      /** 插入图
      * */
     public void InsertImg(Bitmap bmp) {
         SQLiteDatabase db = getWritableDatabase();
         ContentValues cv = new ContentValues();
    
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
    
         cv.put("IMG_DATA", os.toByteArray());
         db.insert("IMGS", null, cv);
    
     }
    
  2. 读取图片列表

     //读取
     public List<Bitmap> ReadImg() {
         SQLiteDatabase db = getReadableDatabase();
         Cursor cr = db.rawQuery("select * from IMGS ", null);
         List<Bitmap> lst = new ArrayList<Bitmap>();
         while (cr.moveToNext()) {
             byte[] in = cr.getBlob(cr.getColumnIndex("IMG_DATA"));
             lst.add(BitmapFactory.decodeByteArray(in, 0, in.length));
         }
         return lst;  } 
    

最后贴上完整的代码:

package demo.cameraDemo;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SlidingDrawer;

public class MainActivity extends Activity {
    Button btnPaizhao;
    CameraHelper mCameraHelper;
    ImageView imageView1;
    BlobDAL mBlobDAL;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBlobDAL = new BlobDAL(this);

        imageView1 = (ImageView) findViewById(R.id.imageView1);

        findViewById(R.id.btnReadDB).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                List<Bitmap> bpArr = mBlobDAL.ReadImg();
                ViewGroup gp = (ViewGroup) findViewById(R.id.div);
                gp.removeAllViews();
                for (int i = 0; i < bpArr.size(); i++) {
                    ImageView iv = new ImageView(MainActivity.this);
                    Bitmap bp = bpArr.get(i);
                    if (bp != null) {
                        iv.setImageBitmap(bp);
                    } else {
                        iv.setImageBitmap(null);
                    }
                    gp.addView(iv);
                }

            }
        });

        btnPaizhao = (Button) findViewById(R.id.btnPaizhao);
        btnPaizhao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mCameraHelper.OnOpenCamera();
            }

        });

        mCameraHelper = new CameraHelper(this);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mCameraHelper.HandleonActivityResult(requestCode, resultCode, data);
    }

    public class CameraHelper {
        Context mContext;

        public CameraHelper(Context ctx) {
            mContext = ctx;
        }

        Uri photoUri;
        public static final int REQUEST_CODE_camera = 2222;

        public void OnOpenCamera() {
            
            //向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一个数据,那么返回标识ID。
            //在完成拍照后,新的照片会以此处的photoUri命名. 其实就是指定了个文件名
            ContentValues values = new ContentValues();
            photoUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            //准备intent,并 指定 新 照片 的文件名(photoUri)
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
            //启动拍照的窗体。并注册 回调处理。
            startActivityForResult(intent, REQUEST_CODE_camera);
        }

        public void HandleonActivityResult(int requestCode, int resultCode,
                Intent data) {
            if (requestCode == CameraHelper.REQUEST_CODE_camera) {

                ContentResolver cr = mContext.getContentResolver();
                if (photoUri == null)
                    return;
                //按 刚刚指定 的那个文件名,查询数据库,获得更多的 照片信息,比如 图片的物理绝对路径
                Cursor cursor = cr.query(photoUri, null, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToNext()) {
                        String path = cursor.getString(1);
                        //获得图片
                        Bitmap bp = getBitMapFromPath(path);
                        imageView1.setImageBitmap(bp);

                        //写入到数据库
                        mBlobDAL.InsertImg(bp);
                    }
                    cursor.close();
                }
                photoUri = null;
            }
        }

        /* 获得图片,并进行适当的 缩放。 图片太大的话,是无法展示的。 */
        private Bitmap getBitMapFromPath(String imageFilePath) {
            Display currentDisplay = getWindowManager().getDefaultDisplay();
            int dw = currentDisplay.getWidth();
            int dh = currentDisplay.getHeight();
            // Load up the image's dimensions not the image itself
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
                    bmpFactoryOptions);
            int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
                    / (float) dh);
            int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
                    / (float) dw);

            // If both of the ratios are greater than 1,
            // one of the sides of the image is greater than the screen
            if (heightRatio > 1 && widthRatio > 1) {
                if (heightRatio > widthRatio) {
                    // Height ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = heightRatio;
                } else {
                    // Width ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = widthRatio;
                }
            }
            // Decode it for real
            bmpFactoryOptions.inJustDecodeBounds = false;
            bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
            return bmp;
        }

    }

    /*
     * 操作数据库
     * */
    class BlobDAL extends SQLiteOpenHelper {

        public BlobDAL(Context context) {
            super(context, "imgDemo.db", null, 1);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String str = "CREATE TABLE [IMGS] ( [IDPK] integer PRIMARY KEY autoincrement,IMG_DATA blob )";
            db.execSQL(str);
        }
        
        /*
         * 插入图
         * */
        public void InsertImg(Bitmap bmp) {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues cv = new ContentValues();

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

            cv.put("IMG_DATA", os.toByteArray());
            db.insert("IMGS", null, cv);

        }

        //读取
        public List<Bitmap> ReadImg() {
            SQLiteDatabase db = getReadableDatabase();
            Cursor cr = db.rawQuery("select * from IMGS ", null);
            List<Bitmap> lst = new ArrayList<Bitmap>();
            while (cr.moveToNext()) {
                byte[] in = cr.getBlob(cr.getColumnIndex("IMG_DATA"));
                lst.add(BitmapFactory.decodeByteArray(in, 0, in.length));
            }
            return lst;
        }



        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
} 

 

<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" >

    <Button
        android:id="@+id/btnPaizhao"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="拍照" />

    <Button
        android:id="@+id/btnReadDB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读数据库-显示刚刚拍的" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000" >
    </View>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="拍照后显示在下面:"
        android:textSize="16sp"
        android:textColor="#FFFFFF"
        android:background="#000000" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:src="@drawable/ic_action_search" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000" >
    </View>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="读取数据库后显示在下面:"
        android:textSize="16sp"
        android:textColor="#FFFFFF"
        android:background="#000000" />
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/div"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout> 

演示代码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容