I am currently reading an image from gallery in Bitmap format. When saving it to the database I need to convert it into byte whilst in the Image Adapter class I need to convert it to bitmap.
The following is the code: - converting to byte in order to store it in database
public void submitAction(View view)
{
/*This method creates a new post and populates it with the data added by the user. The data is then stored in the database
* using the Active Android Library.*/
Post p = new Post();
EditText title = (EditText) findViewById(R.id.post_title_input);
String tit = title.getText().toString();
EditText description = (EditText)findViewById((R.id.editText));
String desc = description.getText().toString();
Bitmap img = yourSelectedImage;
p.title=tit;
p.description=desc;
p.section="science";
int bytes = img.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
img.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
}
Code in imageAdapter class - convert the byte[] to Bitmap
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
/*Converting image to byte*/
Post p = posts.get(position);
byte[] image = p.image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(image);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(theImage);
return imageView;
}
When runnning the application, it is crashing at line Bitmap theImage = BitmapFactory.decodeStream(imageStream); and terminates with a null pointer exception.
Bitmap to byte[]
Bitmap bitmap = ...;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
byte[] to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray.length);
Related
How can I properly change this byte[] photo = getBytes(imageBitmap); to be stored in a database Blob?
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//ImageView imageview = findViewById(R.id.imageView);
//imageview.setImageBitmap(imageBitmap);
//Bitmap to bytes for database
byte[] photo = getBytes(imageBitmap);
Bitmap bmp = BitmapFactory.decodeByteArray(photo, 0, photo.length);
ImageView image = (ImageView) findViewById(R.id.imageView);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));
// DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
// Walk walk = new Walk(photo);
// mydb.addWalk(walk);
}
Have you tried to use the ByteArrayOutputStream?
You can check at the documentation https://developer.android.com/reference/java/io/ByteArrayOutputStream.html
Or to make it ease you can do like this guy did
converting Java bitmap to byte array
`
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
`
First of all, what's the exact problem? Saving the image or storing it into the db?
CREATE TABLE t1 (id INTEGER PRIMARY KEY, data BLOB);
Comes down to this:
InputStream is = context.getResources().open(R.drawable.MyImageFile);
try {
byte[] buffer = new byte[CHUNK_SIZE];
int size = CHUNK_SIZE;
while(size == CHUNK_SIZE) {
size = is.read(buffer); //read chunks from file
if (size == -1) break;
ContentValues cv = new ContentValues();
cv.put(CHUNK, buffer); //CHUNK blob type field of your table
long rawId = database.insert(TABLE, null, cv); //TABLE table name
}
} catch (Exception e) {
Log.e(TAG, "Error saving raw image to: "+rawId, e);
}
i have this annoying problem.Im trying to store image from drawable folder to database then retrieve it and set it in ImageView, but when i try to store it in the ImageView and run it its not changed from the default image that i put in first place, the ImageView is gone.
Here is the code for the activity where the ImageView is and the code for the DB handler. MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.maintestImage);
images();
img.setImageBitmap(dbHandler.getImageDiet());
initNewProf();
initExercises();
}
public void images(){ //get the image from the drawable and store it in the base
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.abs)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
dbHandler.saveDiet(photo);
}` DB handler
public Bitmap getImageDiet(){ //retrive the image from the base
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT imagedata FROM "+ TABLE_DIET, null);
byte[] photo = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
while(c.moveToNext())
{
photo=c.getBlob(3);
}
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imgView.setImageBitmap(theImage);
}
I am a beginner in android. I decoded a Base64 image to Bitmap and i need to compress it to to an Outputstream, now i need to use the Bitmap get added to the ArrayList.
try {
// Getting JSON Array from URL
details = json.getJSONArray(TAG_Root);
for(int i = 0; i < details.length(); i++){
JSONObject c = details.getJSONObject(i);
//Storing JSON item in a Variable
String branch = c.getString(TAG_Branch);
String address = c.getString(TAG_Add);
String uname = c.getString(TAG_User);
String photo = c.getString(TAG_Photo);
System.out.println(photo);
//decoding and compressing bitmap
byte[] imageAsBytes = Base64.decode(photo, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
//bitmap = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
//Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
al_branch.add(branch);
al_add.add(address);
al_user.add(uname);
al_photo.add(bitmap);
}
System.out.println(al_branch);
System.out.println(al_photo);
custom_list adapter = new custom_list(MainActivity.this, al_branch,al_user,al_add ,al_photo);
ImageView img1;
img1 = (ImageView) findViewById (R.id.img1);
URL newurl = new URL("http://10.0.2.2:80/Gallardo/Practice/files/images/donut.jpg");
Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
img1.setImageBitmap(mIcon_val);
I get image from url but I want to store it to my drawable, how?
Everything in the apk will be read only.
So you can't write to drawable.
you have to use "blob" to store image.
ex: to store a image in to db
public void insertImg(int id , Bitmap img ) {
byte[] data = getBitmapAsByteArray(img); // this is a function
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
to retrieve a image from db
public Bitmap getImage(int i){
String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);
if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
return null ;
}
You can also check this saving image to database
You can construct Drawable by using this constructor:
Drawable drawable = new BitmapDrawable(getResources(), mIcon_val);
You can set it to the ImageView like so:
img1.setImageDrawable(drawable);
Its not possible to place image in drawable folder while running the apk.. Saving an image to SDcard is possible..
I'm trying to capture the picture I'm getting from webview.capturePicture() to save it to an sqliteDatabase, to do I need to convert the image to a byte[] to be able to save it as a BLOB in my table, and then by able to retrieve that byte[] and convert it back to a bitmap.
Here is what I'm doing:
Picture p = webView.capturePicture();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
p.writeToStream(bos);
byte[] ba = bos.toByteArray());
I then retrieve the image by:
byte[] image = cursor.getBlob(imageColumnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(image, 0, image.length);
I'm able to retrieve the byte[] just fine but I get a null bitmap all the time from bitmapfactory.
I also notice that if I log.d(TAG, ""+bos) I get a long sequence of bytes as expected but if I do the same to ba just after I do bos.toByteArray() I just get a short array, some thing like this: [B#2b0a7c60
I'm guessing I'm having trouble perhaps to convert by OutputStream to byteArray. Could this by because capturePiture() method returns an OutputStream instead of a ByteArrayOutputStream?
Any help would be appreciated.
Use the below two function convert::::
public String convertBitmapToString(Bitmap src) {
String str =null;
if(src!= null){
ByteArrayOutputStream os=new ByteArrayOutputStream();
src.compress(android.graphics.Bitmap.CompressFormat.PNG, 100,(OutputStream) os);
byte[] byteArray = os.toByteArray();
str = Base64.encodeToString(byteArray,Base64.DEFAULT);
}
return str;
}
public static Bitmap getBitMapFromString(String src) {
Bitmap bitmap = null;
if(src!= null){
byte[] decodedString = Base64.decode(src.getBytes(), Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
}
return bitmap;
}
Updated::
//Convert Picture to Bitmap
private static Bitmap pictureDrawable2Bitmap(Picture picture){
PictureDrawable pictureDrawable = new PictureDrawable(picture);
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}