将图像保存到数据库中

时间:2013-09-11 10:42:30

标签: android database

我想要检索联系人和图像并将它们显示到列表视图中并将图像和联系人保存到数据库中,在另一个活动中我想从数据库中检索带有图像的联系人并将它们显示到列表视图中我能够检索联系人但是如何保存图像进入数据库,之后如何从数据库中检索图像

我使用此方法将数据保存到数据库中

public void addBlockedNumberWithImage(String number, String name,
        byte[] image) {

    // Add a new blocked number
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(BLOCKLIST_NUMBER, number);
    values.put(BLOCKLIST_NAME, name);
    values.put(CONTACT_IMAGE, image);

    /* Inserting the entry */
    db.insert(TABLE_BLOCKLISTWITHIMAGE, null, values);
    db.close(); // close the database connection
}



DbHelper db = new DbHelper(this);
db.addBlockedNumberWithImage(phoneNumber, name, image);

4 个答案:

答案 0 :(得分:3)

而不是将图像保存到数据库中,而是将图像保存到设备上的某个位置(最好是SD卡),并在数据库中保存每个图像的位置

然后,当您想要显示它们时,您只需从数据库中检索图像的路径,然后将其加载:)

答案 1 :(得分:0)

在我的应用程序中,我正在从图库上传图像,我上传的图像要存储在数据库中。但是如何在数据库中存储位图我将位图转换为字符串并保存在数据库中。

Imageupload.class:

public class Imageupload12 extends Activity {
Button buttonLoadImage;
ImageView targetImage;
int i=0;
Database database=new Database(this);
String i1;
String img;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
buttonLoadImage = (Button)findViewById(R.id.loadimage);
targetImage = (ImageView)findViewById(R.id.targetimage);

Bundle b=getIntent().getExtras();
if(b!=null)
{
img=b.getString("image");
targetImage2.setImageURI("image");
//i am getting error as i cant assign string to imageview.

}

buttonLoadImage.setOnClickListener(new Button.OnClickListener(){

public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Log.i("photo",""+intent);
startActivityForResult(intent, i);
i=i+1;
}});

}

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

// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {

case 0:
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
// textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);

i1=bitmap.toString();
Log.i("firstimage........",""+i1);
targetImage.setVisibility(0);

SQLiteDatabase db=database.getWritableDatabase();
db.execSQL("INSERT INTO UPLOAD VALUES('"+i1+"');");

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;

}

}
}

Image.class:

public class Image extends Activity {
Database database=new Database(this);
static EfficientAdapter adapter, adapter1;
static ListView lv1;

static SQLiteDatabase db;
static EfficientAdapter adp;
static Cursor c1;

static Vector<String>IMAGE=new Vector<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

db=database.getReadableDatabase();
c1=db.rawQuery("select * from UPLOAD;", null);

if (c1.moveToFirst()) {

do {
IMAGE.add(c1.getString(0).toString());

} while (c1.moveToNext());

c1.close();
}

lv1=(ListView)findViewById(R.id.List);

adapter=new EfficientAdapter(this);

lv1.setAdapter(adapter);

ImageView add=(ImageView)findViewById(R.id.imv1a);

add.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
IMAGE.clear();

Intent i=new Intent(Image.this,Imageupload12.class);
startActivity(i);

}
});

}

private static class EfficientAdapter extends BaseAdapter{

// protected final Context Context = null;
protected LayoutInflater mLayoutInflater;
AlertDialog.Builder aBuilder;
public EfficientAdapter(Context context) {
// TODO Auto-generated constructor stub
mLayoutInflater=LayoutInflater.from(context);
}

@Override
public int getCount() {
// TODO Auto-generated method stub

return IMAGE.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

final ViewHolder mVHolder;
if(convertView == null){
convertView=mLayoutInflater.inflate(R.layout.pjtlistdetails, parent, false);

mVHolder=new ViewHolder();

mVHolder.t1=(TextView)convertView.findViewById(R.id.pjtdetails);
mVHolder.time=(TextView)convertView.findViewById(R.id.name);

mVHolder.imv=(ImageButton)convertView.findViewById(R.id.editic);
mVHolder.imvd=(ImageView)convertView.findViewById(R.id.delete);
mVHolder.imvf=(ImageView)convertView.findViewById(R.id.fwd);

mVHolder.imv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String img=IMAGE.elementAt(position);
Log.i("image...",""+img);

Context ctx=v.getContext();
Intent myIntent = new Intent();
ctx = v.getContext();
myIntent.setClass(ctx, Imageupload12.class);
myIntent.putExtra("image", img);

ctx.startActivity(myIntent);

IMAGE.clear();

}
});
static class ViewHolder{

ImageButton imv;
ImageView imvd,imvf;
}

从db

中检索图像
public Bitmap getImage(int i){

String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);

if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}

return null ;
}

它是一个非常古老的代码检查它是否有效:)

答案 2 :(得分:0)

使用Base64类,您可以将位图编码为字符串,然后将其存储到数据库中。

可以使用以下示例代码:

Bitmap bitmapOrg =get bitmap from image;

ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

byte[] ba = bao.toByteArray();

String ba1 = Base64.encodeBytes(ba);

现在解码此字符串以使用图像。

答案 3 :(得分:0)

使用SQLiteOpenHelper

从数据库存储和检索图像的示例代码
package com.aliahmad.store_retrive_image;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DataManager extends SQLiteOpenHelper 
{
    public final static String tab="image";
    public final static String col1="iname";
    public final static String col2="id";
    public DataManager(Context context)
    {
        super(context, "MyData", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        db.execSQL("create table image (iname text,id blob)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w(DataManager.class.getName(), "Upgrading database from version "+oldVersion+" to"+newVersion+", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS "+tab);
        onCreate(db);
    }

}

点击商店按钮时调用此功能

public void onStore(View v)
{
    try
    {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        //image is object of Bitmap that you want to store
        image.compress(CompressFormat.PNG, 100, baos);
        byte[] data=baos.toByteArray();
        SQLiteDatabase db=new DataManager(this).getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(DataManager.col1, et.getText().toString());
        cv.put(DataManager.col2, data);
        db.insert(DataManager.tab, null, cv);
    }
    catch (Exception e) {
        Toast.makeText(this, "Errro - "+e,1 ).show();
    }       
}

检索图像调用此函数

public void onRet(View v)
{
    SQLiteDatabase db=new DataManager(this).getReadableDatabase();
    Cursor cr=db.query(DataManager.tab, new String[]{DataManager.col2}, DataManager.col1+"= ?", new String[]{str[which]}, null, null, null);
    if(cr.moveToFirst())
    {
        byte [] b=cr.getBlob(4);
        ByteArrayInputStream imageStream = new ByteArrayInputStream(b); 
        image= BitmapFactory.decodeStream(imageStream);
        iv.setImageBitmap(image);
    }
    else
    {
        Toast.makeText(this, "not found", 1).show();
    }
    db.close();
}