SQLite的使用——图片存储

SQLite的使用——图片存储在上篇有说到SQLite的文本存储,文本的增删改查,在本篇中主要说SQLite对单张图片的存储。简单介绍:SQLiteOpenHelper是一个抽象类。SQLiteOpenHelper中有两个抽象方法,分别是onCreate()和onUpgrade()。SQLiteOpenHelper中还有两个非常重要的实例方法,getReadableDatabase()和getWritableD…

大家好,又见面了,我是你们的朋友全栈君。

在上篇有说到SQLite的文本存储,文本的增删改查,在本篇中主要说SQLite对单张图片的存储。

简单介绍:

SQLiteOpenHelper是一个抽象类。

SQLiteOpenHelper中有两个抽象方法,分别是onCreate()和onUpgrade()。

SQLiteOpenHelper中还有两个非常重要的实例方法,getReadableDatabase()和getWritableDatabase()。

在文章最后仍然会附上DEMO.

先附上一张图

SQLite的使用------图片存储

一、此例与文本例互相独立,继承 SQLiteOpenHelper 类实现的 dbHelper 类。

 

 

public class BitmpUtil extends SQLiteOpenHelper {

	public BitmpUtil(Context context) {
		super(context, "djf", null, 2);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		db.execSQL("Create table img ( id INTEGER PRIMARY KEY AUTOINCREMENT,uname TEXT,uimgae BLOB );");  
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}

二、主界面中选择相册中图片,存储,预览

public class MainActivity extends Activity {

    private Button btnSave, btnQuery;

    private ImageView selectIcon;
    private ImageView showIcon;

    /*数据库操作*/
    private BitmpUtil bu;

    private Bitmap bit;

	
	/*数据库操作*/


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bu = new BitmpUtil(MainActivity.this);

        btnSave = (Button) findViewById(R.id.save);

        btnQuery = (Button) findViewById(R.id.query);

        selectIcon = (ImageView) findViewById(R.id.iv_icon);
        showIcon = (ImageView) findViewById(R.id.iv_showIcon);


        /**
         * 选择图片
         */
        selectIcon.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/*");
                startActivityForResult(intent, 0x1);
            }
        });

        /**
         * 增加
         */
        btnSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                SQLiteDatabase db = bu.getWritableDatabase();

                ContentValues values = new ContentValues();
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                bit.compress(Bitmap.CompressFormat.PNG, 100, os);
                values.put("uimgae", os.toByteArray());
                values.put("uname", "zhangsan");
                db.insert("img", null, values);
                db.close();
                Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_SHORT).show();
            }
        });


        /**
         * 显示图片
         */
        btnQuery.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                SQLiteDatabase db = null;
                db = bu.getReadableDatabase();
                Cursor c = db.query("img", new String[]{"id", "uname", "uimgae"}, "uname=?", new String[]{"zhangsan"}, null, null, null);
                while (c.moveToNext()) {
                    String id = c.getString(c.getColumnIndex("id"));
                    String name = c.getString(c.getColumnIndex("uname"));
                    byte[] in = c.getBlob(c.getColumnIndex("uimgae"));
                    Bitmap bit = BitmapFactory.decodeByteArray(in, 0, in.length);
                    showIcon.setImageBitmap(bit);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            Uri u = data.getData();
            ContentResolver cr = MainActivity.this.getContentResolver();
            try {
                bit = BitmapFactory.decodeStream(cr.openInputStream(u));
                selectIcon.setImageBitmap(bit);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

三、存储核心代码

 SQLiteDatabase db = bu.getWritableDatabase();
                ContentValues values = new ContentValues();
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                bit.compress(Bitmap.CompressFormat.PNG, 100, os);
                values.put("uimgae", os.toByteArray());
                values.put("uname", "zhangsan");
                db.insert("img", null, values);
                db.close();
SQLiteDatabase db = bu.getWritableDatabase();获取数据库,使用ContentValues的对象进行数据插入,使用流写入,最后关闭数据库。

四、读取存储中图片预览

 SQLiteDatabase db = null;
                db = bu.getReadableDatabase();
                Cursor c = db.query("img", new String[]{"id", "uname", "uimgae"}, "uname=?", new String[]{"zhangsan"}, null, null, null);
                while (c.moveToNext()) {
                    String id = c.getString(c.getColumnIndex("id"));
                    String name = c.getString(c.getColumnIndex("uname"));
                    byte[] in = c.getBlob(c.getColumnIndex("uimgae"));
                    Bitmap bit = BitmapFactory.decodeByteArray(in, 0, in.length);
                    showIcon.setImageBitmap(bit);
                }
            }
        });

主要代码已贴

百度网盘:  下载         提取码:aupa

CSDN:下载

下一篇:SQLite多张图片存储

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/158085.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • inputstream和inputstreamreader_FileInputStream

    inputstream和inputstreamreader_FileInputStream使用默认的编码格式解码文件和使用文件原本的编码格式来解码文件importjava.io.*;importjava.util.HashMap;publicclassFuXi2{publicstaticvoidmain(String[]args)throwsIOException{demo01();demo02();}privatestaticvoiddemo02()throws.

    2022年9月26日
  • elasticsearch 使用过程中经常遇到的问题

    elasticsearch 使用过程中经常遇到的问题

    2022年2月20日
  • 服务降级和服务熔断

    服务降级和服务熔断转载自:https://blog.csdn.net/llianlianpay/article/details/79768890 服务熔断  在微服务架构中,微服务之间的数据交互通过远程调用完成,微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,此时如果链路上某个微服务的调用响应时间过长或者不可用,那么对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,导致“雪崩…

    2022年6月7日
  • sql-update 用法

    sql-update 用法update表示更新,要想更新数据库的某条数据,我们通常用:update{表名}set{列名}={新的值}where{条件}以LeetCode上看到的一个简单的题目为例:问题1:将A的薪水修改为8000;答案:updateSalarysetsalarywherename=A;问题2:交换所有的’f’和’m’(即,将所有’f’变为’m’,反之亦然),仅使用单个update语句,…

    2022年10月31日
  • c语言中位运算符的用法_c语言中位运算符的优先级

    c语言中位运算符的用法_c语言中位运算符的优先级位 运 算一直对位运算头疼,在此总结一下   程序中的所有数在计算机内存中都是以二进制的形式储存的。位运算说穿了,就是直接对整数在内存中的二进制位进行操作。运位算包括位逻辑运算和移位运算,位逻辑运算能够方便地设置或屏蔽内存中某个字节的一位或几位,也可以对两个数按位相加等;移位运算可以对内存中某个二进制数左移或右移几位等。计算机内部是以补码形式存放数值的。C语言提供了六种位运算位运算符含义…

    2022年10月5日
  • tcp为什么是三次握手不是两次握手_tcp四次挥手

    tcp为什么是三次握手不是两次握手_tcp四次挥手一、为什么握手是三次,而不是两次或者四次?答:两次不安全,四次没必要。tcp通信需要确保双方都具有数据收发的能力,因此双方都要发送SYN确保对方具有通信的能力二、为什么挥手是四次而不是三次?答:发送FIN包只能表示对方不再发送数据了,不代表对方不再接收数据,因此被动关闭方进行ACK回复之后有可能还会继续发送数据,等到不再发送数据了才会发送下一个FIN包,因此FIN包和ACK包是分开的…

    2022年10月3日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号