Reputation: 1621
i need to save a camera image from sd card to sqlite in android. The problem i am facing is out of memory exception. How i can compress this image and sav it in sqlite. The image format is jpeg
thanks in advance
jibysthomas
Upvotes: 4
Views: 807
Reputation: 1349
I do not know if this is the best way to save storage space using SQLite and I am still looking for it, but here we go.
You can select the source of your image, such as gallery or camera and below is the code.
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();
}
Maybe you need permission to use the camera
@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;
}
}
Here is how to handle the image from the source you selected.
@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();
}
}
}
As you can notice in my example, there is no place to save the image case you selected camera and I placed the image on an ImageView
variable named mProductImage.
From now, you can use a Button to save the image in your SQLite Database. Here is the function you can use for it.
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();
}
}
Where imageViewToByte
functon is:
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;
}
Now you need to implement the SQLiteOpenHelper. You need to create a new class for this. The java file name I used for this was 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) {
}
}
Now you need to implement your CRUD (Create new item, Read, Update and Delete).
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);
}
}
It is important to mention that the compression of the image was made in the onActivityResult()
for both source image (camera and gallery).
with the command:
Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);
Besides that, here is a link where we can read a little bit about compression.
https://androidwave.com/capture-image-from-camera-gallery/
If you have a better way to compress images to save in SQLite Database, please post your code here!
Upvotes: 1