Android jak zapisać obrazy z aparatu w bazie danych i wyświetlić inną aktywność w widoku listy?

Używam aparatu do robienia zdjęć i chcę przechowywać w bazie danych (SQLite). Zapisane zdjęcia muszą być wyświetlane w innym ćwiczeniu z widokiem listy jak ten widok listy images i ten używam tego kodu zrób zdjęcie ale jak przechowywać zdjęcie w bazie danych i wyświetlać w innym ćwiczeniu jakikolwiek pomysł proszę o pomoc .....

Dziękuję....

To jest kod do robienia zdjęć

  public class PhotoActivity extends Activity {
    private static final int CAMERA_REQUEST = 1888; 
    public ImageView imageView;  

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

        this.imageView = (ImageView)this.findViewById(R.id.imageView1);          

        Button B = (Button) this.findViewById(R.id.camera);
        B.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });
    }    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data");   
            imageView.setImageBitmap(photo);                

        }       
    }
}
Author: RajaReddy PolamReddy, 2012-03-30

3 answers

Utwórz klasę pomocniczą bazy danych, taką jak this ..

Podczas przechwytywania obrazu Wstaw obrazek konwertując go na bajty:

Imagehelper help=new Imagehelper(this);

    if (requestCode == CAMERA_REQUEST) {  
                        Bitmap photo = (Bitmap) data.getExtras().get("data");   
                        imageView.setImageBitmap(photo);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byte[] byteArray = stream.toByteArray();

                        help.insert(byteArray);
    }

Aby pobrać z bazy danych:

Imagehelper help=new Imagehelper(this);

       Cursor c= help.getAll();
       int i=0;
       if(c.getCount()>0)
       {  
           Bitmap[]  array=new Bitmap[c.getCount()];
           c.moveToFirst();
           while(c.isAfterLast()==false)
           {

               byte[] bytes=c.getBlob(c.getColumnIndex("imageblob"));

            array[i]=BitmapFactory.decodeByteArray(bytes, 0, 0);
            c.moveToNext();
            i++;
            }
           Log.e("Bitmap length",""+array.length);
       }

Przekaż tę tablicę Bitmap do ListView

 3
Author: Abhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-31 10:47:29

Hej przyjaciele mam rozwiązanie powyższego problemu.Tutaj zamieszczam mój pełny kod źródłowy, aby inni mogli korzystać z tego rozwiązania.

1.Stwórz jeden acyivity czyli Camerapicture Activity.

            public class CameraPictureActivity extends Activity {
                Button addImage;
                ArrayList<Contact> imageArry = new ArrayList<Contact>();
                ContactImageAdapter imageAdapter;
                private static final int CAMERA_REQUEST = 1;

                ListView dataList;
                byte[] imageName;
                int imageId;
                Bitmap theImage;
                DataBaseHandler db;

                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    dataList = (ListView) findViewById(R.id.list);
                    /**
                     * create DatabaseHandler object
                     */
                    db = new DataBaseHandler(this);
                    /**
                     * Reading and getting all records from database
                     */
                    List<Contact> contacts = db.getAllContacts();
                    for (Contact cn : contacts) {
                        String log = "ID:" + cn.getID() + " Name: " + cn.getName()
                                + " ,Image: " + cn.getImage();

                        // Writing Contacts to log
                        Log.d("Result: ", log);
                        // add contacts data in arrayList
                        imageArry.add(cn);

                    }
                    /**
                     * Set Data base Item into listview
                     */
                    imageAdapter = new ContactImageAdapter(this, R.layout.screen_list,
                            imageArry);
                    dataList.setAdapter(imageAdapter);

                    /**
                     * open dialog for choose camera
                     */

                    final String[] option = new String[] {"Take from Camera"};
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.select_dialog_item, option);
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);

                    builder.setTitle("Select Option");
                    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            Log.e("Selected Item", String.valueOf(which));
                            if (which == 0) {
                                callCamera();
                            }


                        }
                    });
                    final AlertDialog dialog = builder.create();

                    addImage = (Button) findViewById(R.id.btnAdd);

                    addImage.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            dialog.show();
                        }
                    });

                }

                /**
                 * On activity result
                 */
                @Override
                protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                    if (resultCode != RESULT_OK)
                        return;

                    switch (requestCode) {
                    case CAMERA_REQUEST:

                        Bundle extras = data.getExtras();

                        if (extras != null) {
                            Bitmap yourImage = extras.getParcelable("data");
                            // convert bitmap to byte
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            byte imageInByte[] = stream.toByteArray();

                            // Inserting Contacts
                            Log.d("Insert: ", "Inserting ..");
                            db.addContact(new Contact("Android", imageInByte));
                            Intent i = new Intent(CameraPictureActivity.this,
                                    CameraPictureActivity.class);
                            startActivity(i);
                            finish();

                        }
                        break;
                    }
                }

                /**
                 * open camera method
                 */
                public void callCamera()
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, CAMERA_REQUEST);
                    intent.setType("image/*");
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", 0);
                    intent.putExtra("aspectY", 0);
                    intent.putExtra("outputX", 250);
                    intent.putExtra("outputY", 200);
                }
                }

2.Utwórz klasę DataBaseHandler.

             public class DataBaseHandler extends SQLiteOpenHelper 
             {

            // All Static variables
            // Database Version
            private static final int DATABASE_VERSION = 1;

            // Database Name
            private static final String DATABASE_NAME = " Camera_imagedb";

            // Contacts table name
            private static final String TABLE_CONTACTS = " Camera_contacts";

            // Contacts Table Columns names
            private static final String KEY_ID = "id";
            private static final String KEY_NAME = "name";
            private static final String KEY_IMAGE = "image";

            public DataBaseHandler(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            // Creating Tables
            @Override
            public void onCreate(SQLiteDatabase db) {
                String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                        + KEY_IMAGE + " BLOB" + ")";
                db.execSQL(CREATE_CONTACTS_TABLE);
            }

            // Upgrading database
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

                // Create tables again
                onCreate(db);
            }

            /**
             * All CRUD(Create, Read) Operations
             */

            public// Adding new contact
            void addContact(Contact contact) {
                SQLiteDatabase db = this.getWritableDatabase();

                ContentValues values = new ContentValues();
                values.put(KEY_NAME, contact._name); // Contact Name
                values.put(KEY_IMAGE, contact._image); // Contact Phone

                // Inserting Row
                db.insert(TABLE_CONTACTS, null, values);
                db.close(); // Closing database connection
            }

            // Getting single contact
            Contact getContact(int id) {
                SQLiteDatabase db = this.getReadableDatabase();

                Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                        KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
                        new String[] { String.valueOf(id) }, null, null, null, null);
                if (cursor != null)
                    cursor.moveToFirst();

                Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                        cursor.getString(1), cursor.getBlob(1));

                // return contact
                return contact;

            }

            // Getting All Contacts
            public List<Contact> getAllContacts() {
                List<Contact> contactList = new ArrayList<Contact>();
                // Select All Query
                String selectQuery = "SELECT  * FROM contacts ORDER BY name";

                SQLiteDatabase db = this.getWritableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                // looping through all rows and adding to list
                if (cursor.moveToFirst()) {
                    do {
                        Contact contact = new Contact();
                        contact.setID(Integer.parseInt(cursor.getString(0)));
                        contact.setName(cursor.getString(1));
                        contact.setImage(cursor.getBlob(2));
                        // Adding contact to list
                        contactList.add(contact);
                    } while (cursor.moveToNext());
                }
                // close inserting data from database
                db.close();
                // return contact list
                return contactList;
            }
            }

3.Utwórz inną klasę Contact

        public class Contact 
        {

            // private variables
            int _id;
            String _name;
            byte[] _image;

            // Empty constructor
            public Contact() {

            }

            // constructor
            public Contact(int keyId, String name, byte[] image) {
                this._id = keyId;
                this._name = name;
                this._image = image;

            }
            public Contact(String name, byte[] image) {
                this._name = name;
                this._image = image;

            }
            public Contact(int keyId) {
                this._id = keyId;

            }

            // getting ID
            public int getID() {
                return this._id;
            }

            // setting id
            public void setID(int keyId) {
                this._id = keyId;
            }

            // getting name
            public String getName() {
                return this._name;
            }

            // setting name
            public void setName(String name) {
                this._name = name;
            }

            // getting phone number
            public byte[] getImage() {
                return this._image;
            }

            // setting phone number
            public void setImage(byte[] image) {
                this._image = image;
            }
        }

4.Utwórz jeden adapter tj. ContactImageAdapter

        public class ContactImageAdapter extends ArrayAdapter<Contact>{
             Context context;
                int layoutResourceId;   
               // BcardImage data[] = null;
                ArrayList<Contact> data=new ArrayList<Contact>();
                public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
                    super(context, layoutResourceId, data);
                    this.layoutResourceId = layoutResourceId;
                    this.context = context;
                    this.data = data;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View row = convertView;
                    ImageHolder holder = null;

                    if(row == null)
                    {
                        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
                        row = inflater.inflate(layoutResourceId, parent, false);

                        holder = new ImageHolder();
                        holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
                        holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
                        row.setTag(holder);
                    }
                    else
                    {
                        holder = (ImageHolder)row.getTag();
                    }

                    Contact picture = data.get(position);
                    holder.txtTitle.setText(picture._name);
                    //convert byte to bitmap take from contact class

                    byte[] outImage=picture._image;
                    ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
                    Bitmap theImage = BitmapFactory.decodeStream(imageStream);
                    holder.imgIcon.setImageBitmap(theImage);
                   return row;

                }

                static class ImageHolder
                {
                    ImageView imgIcon;
                    TextView txtTitle;
                }
            }

5.Na koniec utwórz pliki XML main i screen_list .

5.1 main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ffffff"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:text="Add Image" />

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="0.55"
            android:cacheColorHint="#00000000" >
        </ListView>

    </LinearLayout>

5.2 screen_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="200dp"
        android:layout_height="200dp"
       android:scaleType="fitXY"
        android:gravity="center_vertical" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textSize="14dp"
        android:text="@string/hello"
        android:textColor="#000000"
        android:layout_marginLeft="7dp" />

</LinearLayout>

6.Wyjście w ten sposób. Tutaj wpisz opis obrazka Tutaj wpisz opis obrazka

 6
Author: sachin pangare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-03 11:23:06

Nie jestem przekonany do zapisania samej bitmapy w bazie danych sqlite. Ale jest to możliwe przy użyciu Blob. Blob potrzebuje bajtu [].

Można uzyskać tablicę bajtów zapisując bitmapę (z kompresem) i ponownie odczytując plik. http://developer.android.com/reference/android/graphics/Bitmap.html

Bitmap b;
File f = new File (...);
FileOutputStream fs = new FileOutputStream (f);
b.compress(JPEG, 85, fs);
fs.close ();
// Reread the file f into a byte []

Lub

Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
b.compress(JPEG, 85, baos);
baos.close ();
byte[] blob = baos.toByteArray ();
b.compress(JPEG, 85, baos)
Można też serializować bitmapę do ByteArrayOutputStream (używając ObjectOutputStream)
Bitmap b;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream (baos);
oos.write (b);
oos.close ();
baos.close ();
byte[] blob = baos.toByteArray ();

Jednak, prawdopodobnie ma sens, aby zapisać bitmapy jako pliki (JPG lub PNG), ponieważ mogą one stać się większe. Baza danych będzie przechowywać tylko informacje o ścieżce o tym obrazie.

 2
Author: stefan bachert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-30 12:56:26