【问题标题】:How to save image in storage folder as well as in database when I changed profile picture in android?当我在android中更改个人资料图片时,如何将图像保存在存储文件夹和数据库中?
【发布时间】:2017-06-24 14:28:54
【问题描述】:

我的主要活动有从相机和画廊拍照的代码。

public class MainActivity extends Activity {
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    private ImageView ivImage;
    private String userChoosenTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main11);
        btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
        btnSelect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImage();
            }
        });
        ivImage = (ImageView) findViewById(R.id.ivImage);
    }


    private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library",
                "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity11.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result=Utility.checkPermission(MainActivity11.this);

                if (items[item].equals("Take Photo")) {
                    userChoosenTask ="Take Photo";
                    if(result)
                        cameraIntent();

                } else if (items[item].equals("Choose from Library")) {
                    userChoosenTask ="Choose from Library";
                    if(result)
                        galleryIntent();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
    }

    private void cameraIntent()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
    }

    private void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");

        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ivImage.setImageBitmap(thumbnail);
    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {

        Bitmap bm=null;
        if (data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ivImage.setImageBitmap(bm);
    }

}

它工作正常。但是,我不知道如何将此图像保存到数据库以及存储文件夹中。

【问题讨论】:

    标签: android database camera imageview directory


    【解决方案1】:

    将图像保存在存储文件夹中: MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), bitmap, "检测到的图像", "");

    Sqlite 数据库中的位图:

      public class DatabaseHandler extends SQLiteOpenHelper {
    
    
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "mydatbase12";
    private static final String TABLE_NAME= name
    private static final String KEY_ID = "id";
    //Pancard variable
    private static final String KEY_NAME = "pancard_name";
    private static final String KEY_PHOTO = "Photo";
    
    
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    
    }
    
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DETAIL_TABLE = "CREATE TABLE " + TABLE_NAME+ "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT ,"
              + KEY_PHOTO
                + " blob not null" + ")";
    
    
    
    
        db.execSQL(CREATE_DETAIL_TABLE);
    
        System.out.println("table created ");
    }
    
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME
    
        // Create tables again
        onCreate(db);
        db.close();
    }
    
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
    
    // Adding new PANCARD detail
    public void addData(String data,Bitmap bitmap) {
        SQLiteDatabase db = this.getWritableDatabase();
    
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, data); // tital
        values.put(KEY_PHOTO, Utility.getBytes(bitmap));
        // Inserting Row
    
        db.insert(TABLE_NAME, null, values);
    
        db.close(); // Closing database connection
    }
    

    }

    将图像转换为字节的实用程序类:

      public class Utility {
    
    
    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }
    
    // convert from byte array to bitmap
    public static Bitmap getPhoto(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
    

    }

    所以现在在 addData 方法中传递位图,例如:addData("name",bitmap)

    【讨论】:

    • 这里 Utility.getPhoto(byte[]) 返回 null。不知道为什么?你能帮帮我吗?
    • 你可以得到像这样的位图: byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_PHOTO));位图位图 = Utility.getPhoto(blob)
    • 是的,我得到了那个 blob,然后传递给了 utility.getphoto() 函数。它仍然返回 null。
    • 请查看获取位图的链接:stackoverflow.com/questions/2266030/…
    【解决方案2】:
       File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
    

    // store this imagePath in your database String imagePath = destination.getAbsolutePath();

    谢谢

    【讨论】:

    • 从画廊拍摄的图片怎么样?
    • 将直接存储在您手机的内存中
    【解决方案3】:

    终于解决了我所有的问题:

          private void selectImage() {   
           final CharSequence[] items = { "Choose from Library", "Cancel" };
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
    
                     if (items[item].equals("Choose from Library")) {
                        userChoosenTask ="Choose from Library";
    
                            galleryIntent();
    
                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    
        private void galleryIntent()
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);//
            startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (resultCode == Activity.RESULT_OK) {
                 Uri selectedImageUri = data.getData();
    
                    if (null != selectedImageUri) {
    
                        // Saving to Database...
                        if (saveImageInDB(selectedImageUri)) {
                             //Image Saved in Database...
                            profile_pic.setImageURI(selectedImageUri);
                        }
    
                        // Reading from Database after 3 seconds just to show the message
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (loadImageFromDB()) {
                                    //Image Loaded from Database...
                                }
                            }
                        }, 3000);
                    }
        }
        }
     // Save image in database
        Boolean saveImageInDB(Uri selectedImageUri) {
    
            try {
                dbHelper.open();
                InputStream iStream = getActivity().getContentResolver().openInputStream(selectedImageUri);
                byte[] inputData = Utils.getBytes(iStream);
                dbHelper.editUserImage(inputData,LoginDetails.user_id);
                dbHelper.close();
                return true;
            } catch (IOException ioe) {
                Log.e("EditProfileFragment", "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
                dbHelper.close();
                return false;
            }
    
        }
    //load image from database
        Boolean loadImageFromDB() {
            try {
                dbHelper.open();
                byte[] bytes = dbHelper.retreiveImageFromDB(LoginDetails.user_id);
                dbHelper.close();
                // Show Image from DB in ImageView
                profile_pic.setImageBitmap(Utils.getImage(bytes)); 
                return true;
            } catch (Exception e) {
                Log.e("EditProfileFragment", "<loadImageFromDB> Error : " + e.getLocalizedMessage());
                dbHelper.close();
                return false;
            }  
        }   
      }  
    

    还有我的 util.java

     public class Utils {
    
    public static byte[] getImageBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }
    
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
    
    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
    
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }
    
    public static void slide_down(Context ctx, View v){
    
          Animation a = AnimationUtils.loadAnimation(ctx,R.anim.slide_down);
          if(a != null){
             a.reset();
             if(v != null){
              v.clearAnimation();
              v.startAnimation(a);
             }
          }
       }
      }
    

    dbhelper 函数:

     public void editUserImage(byte[] imageBytes, String user_id ) {
        try{
        ContentValues cv = new ContentValues();
        cv.put(IMAGE, imageBytes);
        mDb.update(USER_TABLE, cv, ID + " = " + user_id + "", null);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
     public byte[] retreiveImageFromDB(String user_id) {
        try{
        Cursor cur = mDb.query(true, USER_TABLE, new String[]{IMAGE},
                ID+"=?",new String[]{user_id}, null, null, null,null);
        if (cur.moveToFirst()) {
            byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
            cur.close();
            return blob;
        }
        cur.close();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    

    这工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      相关资源
      最近更新 更多