用sqlite存储Android手机图片,再从数据库读出图片显示。

废话不多说,直接粘贴代码上来首先建一个数据库类:
 
  
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class Helpersave extends SQLiteOpenHelper{

	public Helpersave(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
		
	}
	public Helpersave(Context context) {
		// TODO Auto-generated constructor stub
		super(context, "SaveImageDemo", null, 1);//这个构造器必须有,activity里会调用;
	}
	@Override
	public void onCreate(SQLiteDatabase jb) {
		// TODO Auto-generated method stub
		jb.execSQL("create table image(image_id integer primary key,bit_image BLOB)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
}
activity:

package com.example.sampleadapterdemo;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
	private static int RESULT_LOAD_IMAGE;
	private static final String TAG = "Result";
	MyHelper helper;
	SQLiteDatabase db;
	Cursor cursor;
	private ListView listView =null;
	private SimpleAdapter adapter ;
	private Button but1;
	private Button but2;
	private ImageView Image;
	private List> list = new ArrayList>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Image = (ImageView) findViewById(R.id.Image1);
		but1 = (Button) super.findViewById(R.id.but1);
		but2 = (Button) super.findViewById(R.id.but2);
		but2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				db = helper.getWritableDatabase();
				cursor = db.query("image", null, null, null, null, null, null);
				if (cursor.moveToFirst()) {

				   // byte[] —> Bitmap
				   byte[] bytes = cursor.getBlob(cursor.getColumnIndex("bit_image"));
				   Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
				   Image.setImageBitmap(bitmap);
				   cursor.close();
					db.close();
					helper.close();
				}


			}
		});
		but1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//一个重定向打开系统图库
				Intent i = new Intent(
						Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
		listView=(ListView) super.findViewById(R.id.listview1);
		String str1="001";
		Object image1 =R.drawable.food_image;
		Map map = new HashMap();
		map.put(str1, image1);
		list.add(map);
		adapter = new SimpleAdapter(getApplicationContext(),
				list,
				R.layout.list,
				new String[]{str1}, 
				new int[]{R.id.image});
		listView.setAdapter(adapter);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
  
            cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
  
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "已经得到bitmap");
            
            //Image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            
            //从手机选择图片插入数据库
           
            Bitmap bitmap = BitmapFactory.decodeFile(picturePath);  
            
            byte[] by = bitmapToBytes(bitmap);
           
           
  
           //cursor = db.query("image", null, null, null, null, null, null);

            ContentValues values = new ContentValues(); 
       
            values.put("image_id", 17);
         
            values.put("bit_image", by);  
       
              
            
           
            db = helper.getWritableDatabase();
        
            db.insert("image", null, values);//插入数据  
     
     
    		db.close();
    	
    		helper.close();
    	
	
	 	
			
		}
	
	}
	 
  
    
	
	 public static byte[] bitmapToBytes(Bitmap bitmap){  
       if (bitmap == null) {  
          return null;  
       }  
       final ByteArrayOutputStream os = new ByteArrayOutputStream();  
       // 将Bitmap压缩成PNG编码,质量为100%存储  
       bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);//除了PNG还有很多常见格式,如jpeg等。  
       return os.toByteArray();  
      } 
      
	}


最后布局文件:



    
    



你可能感兴趣的:(用sqlite存储Android手机图片,再从数据库读出图片显示。)