/**
* 根据图片在数据库中的ID进行读取
* @param strID 图片字段ID
* @param w 需要缩到的宽度
* @param h 需要缩到高度
* @return
*/
public byte[] GetImgByteById(String strID, int w, int h){
//System.out.println("Get img data which id is " + nID)
if(myConnection == null)
this.getConnection()
byte[] data = null
try {
Statement stmt = myConnection.createStatement()
ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID)
StringBuffer myStringBuffer = new StringBuffer()
if (myResultSet.next()) {
java.sql.Blob blob = myResultSet.getBlob(this.strImgName)
InputStream inStream = blob.getBinaryStream()
try {
long nLen = blob.length()
int nSize = (int) nLen
//System.out.println("img data size is :" + nSize)
data = new byte[nSize]
inStream.read(data)
inStream.close()
} catch (IOException e) {
System.out.println("获取图片数据失败,原因:" + e.getMessage())
}
data = ChangeImgSize(data, w, h)
}
System.out.println(myStringBuffer.toString())
myConnection.commit()
myConnection.close()
} catch (SQLException ex) {
System.out.println(ex.getMessage())
}
return data
}
android如何显示blob方法如下:BOLB表示二进制大对象,这种数据类型通过用来保存图片,图象,视频等。
一,使用场景:
http://blog.sina.com.cn/s/blog_8cfbb99201012oqn.html
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
1,重写构造方法
public MySQLiteOpenHelper(Context context, String name,
CursorFactory cursor, int version) {
super(context, name, cursor, version)
}
2, 创建数据库的方法
public void onCreate(SQLiteDatabase db) {
3, 创建一个数据库,表名:imagetable,字段:_id、image。
db.execSQL("CREATE TABLE imagetable (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)")
}
4, 更新数据库的方法
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
5,创建助手类的实例
// CursorFactory的值为null,表示采用默认的工厂类
mySQLiteOpenHelper = new MySQLiteOpenHelper(this, "saveimage.db", null,1)
6, 创建一个可读写的数据库
mydb = mySQLiteOpenHelper.getWritableDatabase()
7,将图片转化为位图
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.erweima)
int size=bitmap1.getWidth()*bitmap1.getHeight()*4
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()
二,从数据库中查询的方法:
1,创建一个指针
Cursor cur=mydb.query("imagetable", new String[]{"_id","image"}, null, null, null, null, null)
byte[] imagequery=null
if(cur.moveToNext()){
2,将Blob数据转化为字节数组imagequery=cur.getBlob(cur.getColumnIndex("image"))
}
3,将字节数组转化为位图
Bitmap imagebitmap=BitmapFactory.decodeByteArray(imagequery, 0, imagequery.length)
iv1=(ImageView) findViewById(R.id.imageView1)
4,将位图显示为图片
iv1.setImageBitmap(imagebitmap)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)