android读取存储mysql图片_android sqlite 图片保存和读出 用流 转字节码

android sqlite 图片保存和读出 用流 转字节码

(2012-04-18 13:15:59)

标签:

it

package com.yiyiweixiao;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

// 重写构造方法

public MySQLiteOpenHelper(Context context, String name,

CursorFactory cursor, int version) {

super(context, name, cursor, version);

}

// 创建数据库的方法

public void onCreate(SQLiteDatabase db) {

// 创建一个数据库,表名:imagetable,字段:_id、image。

db.execSQL("CREATE TABLE imagetable (_id INTEGER PRIMARY KEY

AUTOINCREMENT,image BLOB)");

}

// 更新数据库的方法

public void onUpgrade(SQLiteDatabase db, int oldVersion, int

newVersion) {

}

}

// 创建助手类的实例

// CursorFactory的值为null,表示采用默认的工厂类

mySQLiteOpenHelper = new MySQLiteOpenHelper(this, "saveimage.db",

null,1);

// 创建一个可读写的数据库

mydb = mySQLiteOpenHelper.getWritableDatabase();

//将图片转化为位图

Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),

R.drawable.erweima);

int size=bitmap1.getWidth()*bitmap1.getHeight()*4;

//创建一个字节数组输出流,流的大小为size

ByteArrayOutputStream baos=new ByteArrayOutputStream(size);

//设置位图的压缩格式,质量为100%,并放入字节数组输出流中

bitmap1.compress(Bitmap.CompressFormat.PNG, 100, baos);

//将字节数组输出流转化为字节数组byte[]

byte[] imagedata1=baos.toByteArray();

//将字节数组保存到数据库中

ContentValues cv=new ContentValues();

cv.put("_id", 1);

cv.put("image", imagedata1);

mydb.insert("imagetable", null, cv);

//关闭字节数组输出流

baos.close();

从数据库中查询的方法:

//创建一个指针

Cursor cur=mydb.query("imagetable", new String[]{"_id","image"},

null, null, null, null, null);

byte[] imagequery=null;

if(cur.moveToNext()){

//将Blob数据转化为字节数组imagequery=cur.getBlob(cur.getColumnIndex("image"));

}

//将字节数组转化为位图

Bitmap imagebitmap=BitmapFactory.decodeByteArray(imagequery, 0,

imagequery.length);

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

//将位图显示为图片

iv1.setImageBitmap(imagebitmap);

分享:

a4c26d1e5885305701be709a3d33442f.png喜欢

0

a4c26d1e5885305701be709a3d33442f.png赠金笔

加载中,请稍候......

评论加载中,请稍候...

发评论

登录名: 密码: 找回密码 注册记住登录状态

昵   称:

评论并转载此博文

a4c26d1e5885305701be709a3d33442f.png

发评论

以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值