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

前端之家收集整理的这篇文章主要介绍了用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);
				if (cursor.moveToFirst()) {

				   // byte[] —> Bitmap
				   byte[] bytes = cursor.getBlob(cursor.getColumnIndex("bit_image"));
				   Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,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);
            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);

            ContentValues values = new ContentValues(); 
       
            values.put("image_id",17);
         
            values.put("bit_image",by);  
       
              
            
           
            db = helper.getWritableDatabase();
        
            db.insert("image",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>
原文链接:https://www.f2er.com/sqlite/199763.html

猜你在找的Sqlite相关文章