[英]Android - SQLiteOpenHelper- how to store images directly to database
我有一个SQLite数据库,我直接在其中插入应作为应用程序用户的预存储数据出现的数据。我的代码对于一个图像工作正常,但不知道要转换和检索图像数组
我尝试了位图bitmap = BitmapFactory.decodeResource(getResources()。pmge); 。但是我在解码资源()synatx上造成了错误
码
public class MainActivity extends Activity {
Integer [] pmge ={R.drawable.candle1,R.drawable.candl3,
R.drawable.candl4,R.drawable.candl5,R.drawable.candl6,
R.drawable.lawn,R.drawable.sglc10,R.drawable.senson,R.drawable.thejus6669};
MyDataBase myDataBase;
SQLiteDatabase database;
Cursor c;
ImageView imageView;
byte[] img,img1;
Bitmap b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView=(ImageView)findViewById(R.id.imge);
myDataBase=new MyDataBase(getApplicationContext(),"imagedata",null,1);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.candle1);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
img=bos.toByteArray();
database=myDataBase.getWritableDatabase();
Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);
imageView.setImageBitmap(b1);
}
}
class MyDataBase extends SQLiteOpenHelper{
public MyDataBase(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table tableimage (image BLOB,);");
db.execSQL("INSERT INTO tableimage(image) VALUES(img) ");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
您必须使用BLOB格式将图像存储在Table中。您应该将Image转换为流然后存储它。我希望这一点对您有所帮助:)
将图像转换为位图,然后将位图转换为byte [],然后将其作为Blob存储在数据库中。
要将位图转换为字节[],可以使用以下命令:
Bitmap yourBitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
而不是用于检索/获取图像
byte[] byteArray = DBcursor.getBlob(columnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
不,您不能将图像直接存储到数据库中,可以通过多种方法进行。 例如
首先,您需要在表中创建BLOB类型的字段。
第二步,将图像转换为字节数组。
最后,将该字节数组存储/推入数据库表中数据类型为BLOB的特定列
我建议不要将图像直接存储在数据库中。 只需将图像存储在特定路径上,然后将指向该图像的路径存储在数据库中即可。
检查此答案: https : //stackoverflow.com/a/3751/1739882
不推荐将文件存储在数据库中的原因:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.