从sqlite中检索图像

时间:2014-03-10 07:56:50

标签: android sqlite

我创建了一个包含surveyname和image的数据库。图像以正确的字节(BLOB)形式插入到数据库中,但是当我试图检索图像时,它会给出一些随机值。当我使用if条件查找图像时,它返回一个随机值,当我使用它时,它导致随机值无限循环。

public class CaptureSignature extends Fragment implements OnClickListener {
     LinearLayout mContent;
        signature mSignature;
        Button mClear, mGetSign, mCancel;
        public static String tempDir;
        public int count = 1;
        public String current = null;
        private Bitmap mBitmap;
        View mView;
        File mypath;
        Context context;

        private String uniqueId;
        private EditText yourName;
       // private DatabaseMethods db;
       // private DatabaseHandler db;
        DatabaseMethods db=new DatabaseMethods(getActivity());
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
        }
        //@Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        db=new DatabaseMethods(getActivity());
        //db=new DatabaseHandler(getActivity());
        //db.open();

        //Toast toast = Toast.makeText(context,"hj", Toast.LENGTH_SHORT);
        //toast.show();
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewFrag = inflater.inflate(R.layout.signature, container, false);
         //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
         // DatabaseMethods db=new DatabaseMethods(this);

         tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
         ContextWrapper cw = new ContextWrapper(getActivity());
         File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
         prepareDirectory();
         uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
         current = uniqueId + ".png";
         mypath= new File(directory,current);
         Log.e("path"," "+mypath);
         mContent = (LinearLayout)viewFrag. findViewById(R.id.linearLayout);
         mSignature = new signature(getActivity(), null);
         mSignature.setBackgroundColor(Color.WHITE);
         mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
         mClear = (Button)viewFrag.findViewById(R.id.clear);
         mGetSign = (Button)viewFrag.findViewById(R.id.getsign);
         mGetSign.setEnabled(false);
         mCancel = (Button)viewFrag.findViewById(R.id.cancel);
         mView = mContent;
         yourName = (EditText)viewFrag.findViewById(R.id.yourName);

            mClear.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Cleared");
                    mSignature.clear();
                    mGetSign.setEnabled(false);
                }
            });

            mGetSign.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Saved");
                    boolean error = captureSignature();
                    if(!error){
                        mView.setDrawingCacheEnabled(true);
                        mSignature.save(mView);
                        /*Bundle b = new Bundle();
                        b.putString("status", "done");
                        Intent intent = new Intent();
                        intent.putExtras(b);
                        setResult(RESULT_OK,intent);  
                        finish();*/
                    }
                }
            });

            mCancel.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Canceled");
                    /*Bundle b = new Bundle();
                    b.putString("status", "cancel");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);
                    finish();*/
                }
            });
        return viewFrag;
        }

       /* @Override
            protected void onDestroy() {
            Log.w("GetSignature", "onDestory");
            super.onDestroy();
        }*/

        private boolean captureSignature() {

            boolean error = false;
            String errorMessage = "";


            if(yourName.getText().toString().equalsIgnoreCase("")){
                errorMessage = errorMessage + "Please enter your Name\n";
                error = true;
            }  

            if(error){
                Toast toast = Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 105, 50);
                toast.show();
            }

            return error;
        }

        private String getTodaysDate() {

            final Calendar c = Calendar.getInstance();
            int todaysDate =     (c.get(Calendar.YEAR) * 10000) +
            ((c.get(Calendar.MONTH) + 1) * 100) +
            (c.get(Calendar.DAY_OF_MONTH));
            Log.w("DATE:",String.valueOf(todaysDate));
            return(String.valueOf(todaysDate));

        }

        private String getCurrentTime() {

            final Calendar c = Calendar.getInstance();
            int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) +
            (c.get(Calendar.MINUTE) * 100) +
            (c.get(Calendar.SECOND));
            Log.w("TIME:",String.valueOf(currentTime));
            return(String.valueOf(currentTime));

        }


        private boolean prepareDirectory()
        {
            try
            {
                if (makedirs())
                {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(context, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
                return false;
            }
        }

        private boolean makedirs()
        {
            File tempdir = new File(tempDir);
            if (!tempdir.exists())
                tempdir.mkdirs();

            if (tempdir.isDirectory())
            {
                File[] files = tempdir.listFiles();
                for (File file : files)
                {
                    if (!file.delete())
                    {
                        System.out.println("Failed to delete " + file);
                    }
                }
            }
            return (tempdir.isDirectory());
        }

        public class signature extends View
        {
            private static final float STROKE_WIDTH = 5f;
            private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
            private Paint paint = new Paint();
            private Path path = new Path();
            Context context;

            private float lastTouchX;
            private float lastTouchY;
            private final RectF dirtyRect = new RectF();

            public signature(Context context, AttributeSet attrs)
            {
                super(context, attrs);
                paint.setAntiAlias(true);
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeJoin(Paint.Join.ROUND);
                paint.setStrokeWidth(STROKE_WIDTH);
            }

            public void save(View v)
            {
                Log.v("log_tag", "Width: " + v.getWidth());
                Log.v("log_tag", "Height: " + v.getHeight());
                if(mBitmap == null)
                {
                    mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
                }
                Canvas canvas = new Canvas(mBitmap);
                try
                {
                    FileOutputStream mFileOutStream = new FileOutputStream(mypath);
                    v.draw(canvas);
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                    Log.e("imageinto",""+mBitmap);
                    mFileOutStream.flush();
                    mFileOutStream.close();
                    String url = Images.Media.insertImage(getActivity().getContentResolver(), mBitmap, "title", null);
                    Log.v("log_tag","url: " + url);
                    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90,baos);
                    byte[] byteData=baos.toByteArray();
                    Log.e("imageintobyedata",""+byteData);
                    Bitmap bmp=BitmapFactory.decodeByteArray(byteData,0,byteData.length);
                    Log.e("imageretrieved",""+bmp);
                    db.open();
                    Log.e("after","database open");
                    db.storeImage(byteData);
                    //In case you want to delete the file
                    //boolean deleted = mypath.delete();
                    //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                    //If you want to convert the image to string use base64 converter

                }
                catch(Exception e)
                {
                    Log.v("log_tag", e.toString());
                }
            }

            public void clear()
            {
                path.reset();
                invalidate();
            }

            @Override
            protected void onDraw(Canvas canvas)
            {
                canvas.drawPath(path, paint);
            }

            @Override
            public boolean onTouchEvent(MotionEvent event)
            {
                float eventX = event.getX();
                float eventY = event.getY();
                mGetSign.setEnabled(true);

                switch (event.getAction())
                {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    lastTouchX = eventX;
                    lastTouchY = eventY;
                    return true;

                case MotionEvent.ACTION_MOVE:

                case MotionEvent.ACTION_UP:

                    resetDirtyRect(eventX, eventY);
                    int historySize = event.getHistorySize();
                    for (int i = 0; i < historySize; i++)
                    {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                        path.lineTo(historicalX, historicalY);
                    }
                    path.lineTo(eventX, eventY);
                    break;

                default:
                    debug("Ignored touch event: " + event.toString());
                    return false;
                }

                invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                        (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

                lastTouchX = eventX;
                lastTouchY = eventY;

                return true;
            }

            private void debug(String string){
            }

            private void expandDirtyRect(float historicalX, float historicalY)
            {
                if (historicalX < dirtyRect.left)
                {
                    dirtyRect.left = historicalX;
                }
                else if (historicalX > dirtyRect.right)
                {
                    dirtyRect.right = historicalX;
                }

                if (historicalY < dirtyRect.top)
                {
                    dirtyRect.top = historicalY;
                }
                else if (historicalY > dirtyRect.bottom)
                {
                    dirtyRect.bottom = historicalY;
                }
            }

            private void resetDirtyRect(float eventX, float eventY)
            {
                dirtyRect.left = Math.min(lastTouchX, eventX);
                dirtyRect.right = Math.max(lastTouchX, eventX);
                dirtyRect.top = Math.min(lastTouchY, eventY);
                dirtyRect.bottom = Math.max(lastTouchY, eventY);
            }
        }

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

        }
    }


public class DatabaseMethods {
        private static final String databaseName = "Demo11";  
        private static final int databaseVersion = 10;

        private static final String imagestable =  
                "CREATE TABLE IF NOT EXISTS image (SURVEYNAME TEXT,IMAGE BLOB);";  
        private final Context context;   
        private DatabaseHelper DBHelper;  
        private SQLiteDatabase db;  
        Cursor cursor;  
        int count;  
        boolean isProjectNamePresent=false;  
        boolean isProfileNamePresent = false;  

        public DatabaseMethods(Context ctx)   
        {  
            Log.e("inside","database method");
            this.context = ctx;  
            DBHelper = new DatabaseHelper(context);  
        }  

        private static class DatabaseHelper extends SQLiteOpenHelper   
        {  

            public DatabaseHelper(Context context)   
            {  

                super(context, databaseName, null, databaseVersion);  
            }  
            @Override  
            public void onCreate(SQLiteDatabase db)   
            {  
                 Log.e("insideOnCreate","database method1");  
                db.execSQL(imagestable);  
            }  

            @Override  
            public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion)   
            {  

                db.execSQL("DROP TABLE IF EXISTS image");  
                onCreate(db);  
            }  

        }      

        //---opens the database---  
        public DatabaseMethods open() throws SQLException   
        {     
            db = DBHelper.getWritableDatabase();  
            return this;  
        }  

        //---closes the database---      
        public void close()   
        {  
            DBHelper.close();  
        } 


        public void getAllRecords()
        {
            String survey="mobile";
            String query="SELECT IMAGE FROM image WHERE SURVEYNAME='"+survey+"'";

            //SQLiteDatabase db=this.getWritableDatabase();
            Cursor c=db.rawQuery(query,null);
            int col=c.getColumnIndex("IMAGE");
            Log.e("columnindex",""+col);
            if(c.moveToFirst())
            {
                byte[] blobData=c.getBlob(col);
                Log.e("cursorimage",""+blobData);
            }
        }


 public void storeImage(byte[] imgData)  
    {  
        String query; 
        String image1=imgData.toString();
        String survey="mobile";
        Log.e("imagename",image1);
        query = "INSERT INTO image (SURVEYNAME,IMAGE) 
        VALUE('"+survey+"','"+imgData+"')";
        Toast.makeText(context,"ImageInserted",Toast.LENGTH_LONG).show();
        db.execSQL(query);  
    }




    }

3 个答案:

答案 0 :(得分:1)

我找到了我的问题的altaernate解决方案我使用base64解码了我的图像并将其保存为varchar然后再次编码。它为我工作...... 1.我的捕获图像文件

ByteArrayOutputStream baos=new  ByteArrayOutputStream();
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90,baos);
                    byte[] byteData=baos.toByteArray();
                    String imageEncoded=Base64.encodeToString(byteData,Base64.DEFAULT);
  1. 数据库文件

    private static final String imagestable =
                “CREATE TABLE IF NOT NOT EXISTS image(SURVEYNAME TEXT,IMAGE VARCHAR2(500));”;

    public void storeImage(byte [] imgData)
        {
            字符串查询;         String image1 = imgData.toString();         字符串调查=“移动”;         Log.e( “imagename”,图像1);         query =“INSERT INTO image(SURVEYNAME,IMAGE)VALUES('”survey +“','”+ imgData +“')”;         Toast.makeText(上下文中, “ImageInserted”,Toast.LENGTH_LONG).show();         db.execSQL(查询);
        }

  2. 解码

    byte [] decodeByteArray = Base64.decode(image,0);         位图bmp = BitmapFactory.decodeByteArray(decodeByteArray,0,decodeByteArray.length);         Log.e( “BITMAPCONVERSION”, “” + BMP);         img.setImageBitmap(BMP);

答案 1 :(得分:0)

要从字节中取回图像,您需要将字节转换为位图,如:

byte[] imgBytes;
Bitmap bm = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
imageView.setImageBitmap(bm);

//其中imgBytes是来自数据库的字节

答案 2 :(得分:0)

这是另一种方法。在设备上下载图像并将图像路径保存在数据库中,并在需要时使用该路径。