压缩相机图像并将其保存在Android中的Sqlite中

时间:2011-10-30 13:37:10

标签: android


我需要将sd卡中的摄像头图像保存到android中的sqlite。我面临的问题是内存不足异常。我如何压缩这个图像并在sqlite中保存它。图像格式为jpeg
提前谢谢你 jibysthomas

1 个答案:

答案 0 :(得分:0)

我不知道这是否是使用SQLite节省存储空间的最佳方法,我仍然在寻找它,但是我们开始吧。

您可以选择图像的来源,例如画廊或照相机,下面是代码。

private void selectProductImage() {
        final CharSequence[] itens = {"Use Camera", "Gallery", "Cancel"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialog);
        builder.setItems(itens, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (itens[which].equals("Use Camera")) {
                    Toast.makeText(YourActivity.this, "Use Camera", Toast.LENGTH_SHORT).show();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
                    } else {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST);
                    }

                } else if (itens[which].equals("Gallery")) {
                    Toast.makeText(YourActivity.this, "Gallery", Toast.LENGTH_SHORT).show();
                    Intent galleryIntent = new Intent();
                    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, REQUEST_GALLERY_PHOTO);

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

也许您需要使用摄像头的许可权

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MY_CAMERA_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            } else {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

    }

以下是处理来自所选来源的图像的方法。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
        Bitmap bitmap = Bitmap.createScaledBitmap((Bitmap) data.getExtras().get("data"),96, 96, true);
        mProductImage.setImageBitmap(bitmap);
        isPriviteImage = true;
    }

    if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK && data != null) {
        //mProductImage.setImageURI(data.getData());

        // INSERT IMAGE INTO SQLite
        Uri uri = data.getData();

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(inputStream),96, 96, true);
            mProductImage.setImageBitmap(bitmap);
            isPriviteImage = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

在您的示例中您会注意到,没有地方可以保存您选择相机的图像保护套,并且我将图像放置在名为 mProductImage 的变量ImageView上strong>。

从现在开始,您可以使用按钮将图像保存在SQLite数据库中。这是您可以使用的功能。

private void saveImage() {

    productTablePath = Environment.getExternalStorageDirectory()+"/YourAditionalPath/";

    ProductDatabaseHelper productDatabaseHelper = new ProductDatabaseHelper(getApplicationContext(), "dbname.db", productTablePath);
    productListTable = productDatabaseHelper.getWritableDatabase();
    productRepository = new ProductRepository(productListTable);

    try {

        if (isPriviteImage) {
            productRepository.addProduct(imageViewToByte(mProductImage));
            isPriviteImage = false;

        } else {
            productRepository.addProduct(null);

        }

        mProductImage.setImageResource(R.drawable.shopping_cart_black_48dp);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

imageViewToByte功能在哪里:

private byte[] imageViewToByte(CircleImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

现在,您需要实现 SQLiteOpenHelper 。您需要为此创建一个新类。我为此使用的Java文件名是 ProductDatabaseHelper.java

public class ProductDatabaseHelper extends SQLiteOpenHelper {

    private static int dbVersion = 1;

    public ProductDatabaseHelper(Context context, String name, String storageDirectory) {
        super(context, storageDirectory+name, null, dbVersion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        StringBuilder sql = new StringBuilder();

        sql.append("CREATE TABLE IF NOT EXISTS PRODUCTLIST (");

        sql.append("        IMAGE        BLOB,");


        db.execSQL(sql.toString());

    }

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

    }
}

现在,您需要实施CRUD(创建新项目,读取,更新和删除)。

public class ProductRepository {

    SQLiteDatabase instance;

    public ProductRepository(SQLiteDatabase instance) {
        this.instance = instance;
    }

    public void addProduct(byte[] image){

        ContentValues contentValues = new ContentValues();

        contentValues.put("IMAGE",image);

        instance.insertOrThrow("PRODUCTLIST",null, contentValues);
    }


}

重要的是要提到,图像的压缩是在onActivityResult()中对两个原始图像(相机和图库)进行的。

使用命令:

Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);

除此之外,这是一个链接,在这里我们可以阅读一些有关压缩的信息。

https://androidwave.com/capture-image-from-camera-gallery/

如果您有更好的方法来压缩图像以保存到SQLite数据库中,请在此处发布您的代码!