用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
		
	}
	
}</span>
activity:

<span style="font-family:Microsoft YaHei;font-size:18px;">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<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
	@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<String, Object> map = new HashMap<String, Object>();
		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();  
      } 
      
	}</span>


最后布局文件:

<span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:visibility="gone"/>
    <Button 
        android:id="@+id/butopen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button 
        android:id="@+id/butsave"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />
    <Button 
        android:id="@+id/butshow"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"/>
	<ImageView 
	    android:id="@+id/Image"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    />
	<ImageView 
	    android:id="@+id/imageshow"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"/>
</LinearLayout></span>



  • 2
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值