Compress a camera image and save it in Sqlite in androidIs there a way to run Python on Android?How do save an Android Activity state using save instance state?Strange out of memory issue while loading an image to a Bitmap objectLazy load of images in ListViewSave bitmap to locationClose/hide the Android Soft KeyboardWhy is the Android emulator so slow? How can we speed up the Android emulator?Is there a unique Android device ID?What is 'Context' on Android?Proper use cases for Android UserManager.isUserAGoat()?
declaring a variable twice in IIFE
What would happen to a modern skyscraper if it rains micro blackholes?
Can a German sentence have two subjects?
Draw simple lines in Inkscape
Download, install and reboot computer at night if needed
Example of a relative pronoun
What would the Romans have called "sorcery"?
Patience, young "Padovan"
Why was the small council so happy for Tyrion to become the Master of Coin?
Email Account under attack (really) - anything I can do?
Could a US political party gain complete control over the government by removing checks & balances?
Is it possible to do 50 km distance without any previous training?
What is the white spray-pattern residue inside these Falcon Heavy nozzles?
Japan - Plan around max visa duration
Concept of linear mappings are confusing me
Are there any consumables that function as addictive (psychedelic) drugs?
A Journey Through Space and Time
Why don't electron-positron collisions release infinite energy?
I probably found a bug with the sudo apt install function
How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?
Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?
The use of multiple foreign keys on same column in SQL Server
What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?
How can I fix this gap between bookcases I made?
Compress a camera image and save it in Sqlite in android
Is there a way to run Python on Android?How do save an Android Activity state using save instance state?Strange out of memory issue while loading an image to a Bitmap objectLazy load of images in ListViewSave bitmap to locationClose/hide the Android Soft KeyboardWhy is the Android emulator so slow? How can we speed up the Android emulator?Is there a unique Android device ID?What is 'Context' on Android?Proper use cases for Android UserManager.isUserAGoat()?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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
android
add a comment |
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
android
3
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34
add a comment |
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
android
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
android
android
asked Oct 30 '11 at 13:37
jibysthomasjibysthomas
75311023
75311023
3
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34
add a comment |
3
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34
3
3
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34
add a comment |
1 Answer
1
active
oldest
votes
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!
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7945217%2fcompress-a-camera-image-and-save-it-in-sqlite-in-android%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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!
add a comment |
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!
add a comment |
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!
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!
answered Mar 9 at 3:24
Aliton OliveiraAliton Oliveira
8018
8018
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7945217%2fcompress-a-camera-image-and-save-it-in-sqlite-in-android%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Its not a good idea to save binary data in sqlite, I would recommend saving the file path in the database.
– Alan Moore
Oct 30 '11 at 13:39
We have made a comparison of both approach: I definitely agree with Alan… So, save the picture somewhere and store the uri in the db.
– Renaud
Oct 30 '11 at 13:43
The images need to be private for the application so i have to done so
– jibysthomas
Oct 30 '11 at 14:34