看到网上很多人都用下面的几种方式保存图片到数据据,感觉蛮靠谱的,之前我转载的那些方法貌似都不管用(也可能是我不会用),今晚先收藏,明天或者有空的时候再试试下面的方法,先收藏:
更新
SQLiteDatabase db;
String args[] = {id};
ContentValues cv = new ContentValues();
cv.put("android123", id);
Cursor c = db.rawQuery("SELECT * FROM table WHERE android123=?", args); 执行本地SQL语句查询
if (c.getCount() != 0) {
//dosomething
ContentValues cv = new ContentValues();
cv.put("android123","cwj");
db.insert("table", "android123", cv); //插入数据
String args[] = {id};
ContentValues cv2= new ContentValues();
cv2.put("android123", id);
db.delete("table", "android123=?", args); //删除数据
}
网上第一个版本:
一、数据库创建和存取方法:
在数据库创建时,图片字段的数据类型存储为 BLOB数据库插入操作
public void onCreate(SQLiteDatabase db)
{
String sql = "create table " + TB_NAME + " ( " + ID + " integer primary key , " + IMAGE + " BLOB ) ";
db.execSQL(sql);
}
将图片一字节形式存储数据库读取操作
public long insert(byte[] img)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(IMAGE, img);
long result = db.insert(TB_NAME, null, cv);
return result;
}
得到的图片是Bitmap类型,参数position 点击图片在ListView、GridView等内的位置 ,可根据需要编写代码二
public Bitmap getBmp(int position)
{
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = select(TB_NAME);
cursor.moveToPosition(position);
byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
return bmpout;
}
二、将图片转化为 byte[]//参数id为图片资源 (R.drawable.img)
public byte[] img(int id)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(id)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
db.execSQL(sql);
ContentValues cv = new ContentValues();
cv.put(IMAGE, img);
long result = db.insert(TB_NAME, null, cv);
return result;
Cursor cursor = select(TB_NAME);
cursor.moveToPosition(position);
byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
return bmpout;
Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(id)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
可惜我想要的是能一连串的查询,查询的时候有文字和图片一起都查到, 上面这种暂时不是我想要的,下面这个人的感觉蛮可以,他应该是验证过的, 应该是我想要了的吧,
网上第二个版本
转自http://blog.sina.com.cn/s/blog_539070ad0100nesa.html
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
// 数据操作类
public class testSeedDB {
}
// 读文件到 BYTE 来自网上未验证
//http://www.a3gs.com/BookViews.asp?InfoID=2865&ClassID=935
导入包:
import
import
import
import
实现代码:
public
}