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..
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);
}
In the code below, you can see that I have created an imageview using a bitmap. What I want to know is how I can save an image of that imageview to my camera roll. Thanks!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.key_code_zoom);
title = (TextView) findViewById(R.id.accountTitleLarge);
imageView = (ImageView) findViewById(R.id.keyCodeLarge);
Intent callingActivity = getIntent();
Bundle callingBundle = callingActivity.getExtras();
if (callingBundle != null) {
String titleText = callingBundle.getString("title");
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
title.setText(titleText);
imageView.setImageBitmap(bmp);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
supportFinishAfterTransition();
}
});
}
To save an image in gallery, you must first get the bitmap and then save it.
private void imageToRoll(){
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache(); // Gets the Bitmap
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, imagTitle , imageDescription); // Saves the image.
}
Also, set the permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you are looking for some code that will help you save the Image from the ImageView to your phone storage then the following code will help you
public String getImageFromView() {
imageview.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imageview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageview.layout(0, 0, imageview.getMeasuredWidth(), imageview.getMeasuredHeight());
imageview.buildDrawingCache(true);
//Define a bitmap with the same size as the view
Bitmap b = imageview.getDrawingCache();
String imgPath = getImageFilename();
File file = new File(imgPath);
try {
OutputStream os = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, os);
os.flush();
os.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, "NST");
image.put(Images.Media.DISPLAY_NAME, imgPath.substring(imgPath.lastIndexOf('/')+1));
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = file.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, file.length());
image.put(Images.Media.DATA, file.getAbsolutePath());
Uri result = mContext.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgPath;
}
you will have to provide a file path getImageFilename();this function provides the path where the file is suppose to be stored. The ContentValues will be responsible to let the images be scanned in gallery.
Hope this helps.
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 storing an image taken from camera into sqlite database can anybody help me to retrieve the same image and i want to show that image in a image view.
Here is my Database handler class method for saving the image
public long insert(Bitmap img ) {
SQLiteDatabase base=this.getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value=new ContentValues();
value.put("image",data);
long a= base.insert("Mypic", null, value);
System.out.println("check1" + a);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
Please help me for writing the method how i can get the image and display the image in an imageview.
To insert Image on database:
Bitmap bitmap = ((BitmapDrawable) image_imgv.getDrawable()).getBitmap();
ByteArrayOutputStream bos4 = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.PNG, 100, bos4);
image = bos4.toByteArray();
database = new BBDD(this, "BBDD", null, 1);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues reg = new ContentValues();
reg.put("img", image);
To retrieve:
database2 = new BBDD(Activity.this, "BBDD", null, 1);
SQLiteDatabase db2 = database2.getReadableDatabase();
if (db2 != null)
{
Cursor cursor = db2.rawQuery("SELECT img FROM database2, null);
if (cursor.moveToFirst())
{
img=cursor.getBlob(cursor.getColumnIndex("img"));
Bitmap b1=BitmapFactory.decodeByteArray(image, 0, image.length);
image_imageview.setImageBitmap(b1);
}
else
Toast.makeText(Activity.this, "Error.", Toast.LENGTH_LONG).show();
db2.close();
}
else
Toast.makeText(sActivity.this, "Error db.", Toast.LENGTH_LONG).show();
}
});
I'm new to android development. I am able to restore string from my sqite Database to my listview. Now I want to add image to my listview via the image's path that I saved to my Database(I was able to save the path already, my only problem is how do I add that path in my code below). Here's my code:
private void populateFields() {
// if the row is not null from the database.
if (mRowId != null) {
cursor = studentsDbAdapter.queueStud(mRowId);
String[] from = new String[]{StudentsDbAdapter.KEY_StudentName,StudentsDbAdapter.KEY_StudentID,StudentsDbAdapter.KEY_Course,StudentsDbAdapter.KEY_Year,StudentsDbAdapter.KEY_Contact,StudentsDbAdapter.KEY_Email};
int[] to = new int[]{R.id.textstud,R.id.textstudID};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.stud_row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
}
}
I don't know if this is gonna help but in my other activity where I saved the image's path I was able to restore the image by using the following code:
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false) {
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if (image.exists()) {
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}
You have to make custom adapter.
In adapter you can display image like this,
public static void ShowPicture(String fileName, ImageView pic) {
File f = new File(Environment.getExternalStorageDirectory(), fileName);
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ",String.format( "ShowPicture.java file[%s]Not Found",fileName));
return;
}
Bitmap = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}
How are you storing your image in DB ?
If Stored as blob, use BitmapFactory to convert it to Bitmap and set it to ImageView.
Or if it is stored as Base64 encoded string, then decode it and convert it to Bitmap.