How to set Image on ImageButton dynamically? - android

I want to set an image on a button in my app, dynamically from a file on the sdcard. I have tried this code but it is not working. I have tried to convert the image to a bitmap object and I set that object to ImageButton, but it isn't showing anything. How can I solve this issue?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File imageFile = new File("/sdcard0/DCIM/camera/jbn.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);
}
XML
<ImageButton
android:layout_width="200dip"
android:layout_height="200dip"
android:id="#+id/imgBtn"
/>
Algorithm
void loadPic()
{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/camera/";
File parentDir=new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate;
String lastFileName;
boolean isFirstFile = true; //just temp variable for being sure that we are on the first file
for (File file : files) {
if(isFirstFile){
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if(file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")){
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
}
}
}

Try with something simple like this for example:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "jbn.jpg";
String pathName = baseDir + "/your/folder(s)/" +_ fileName; //maybe your folders are /DCIM/camera/
Bitmap bmp = BitmapFactory.decodeFile(pathName);
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);

Try to get get AbsolutePath of image file :
File imageFile = new File("/sdcard0/DCIM/camera/jibin.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

You can try something like this -
String path = Environment.getExternalStorageDirectory()
+ "/Images/test.jpg";
File imgFile = new File(path);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(myBitmap);
}

If you want to set the image dynamically from any URL that you have, set the image in this way. You can also set the bitmap width and height.
private class LoadImage extends AsyncTask<Bundle, String, Bitmap> {
Bitmap bitmap;
#Override
protected Bitmap doInBackground(Bundle... args) {
extras=args[0];
try {
InputStream in = new java.net.URL("Enter your URL").openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
imageButton.setImageBitmap(image);
}
}
And if you want to set the image from the local directory or from the resources folder then just fetch the Image from the folder and set that in image and you don't need to convert it into a Bitmap.
Thanks

Related

Save drawable to string and convert the string to bitmap from the saved string?

I am trying to save the themes. I have themes(images) in drwable folder. I am showing the list of images and on click of the same I want to save the selected drawable resource in sharedpreferences and get the same from sharedpreferences.
To do that I thought to convert the drawable resourse into an uri and convert uri to string.
I tried to convert the drawable to uri like below :
public static String getURLForResource (int resourceId,Context context) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
/* return Uri
.parse("android.resource://"+ BuildConfig.APPLICATION_ID +
"/" +resourceId).toString();*/
Resources resources = context.getResources();
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ resources.getResourcePackageName(resourceId) + '/'
+ resources.getResourceTypeName(resourceId) + '/'
+ resources.getResourceEntryName(resourceId)).toString();
}
and retriving this uri string from sharedprefences and trying to convert it to bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap =
BitmapFactory.decodeFile(sharedPreferencesData.getStr(
"ThemeName"),
options);*/
/* Uri myUri = Uri.parse(sharedPreferencesData.getStr(
"ThemeName"));
*/
/* Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
ContentResolver res = getContentResolver();
InputStream in = null;
try {
in = res.openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap artwork = BitmapFactory.decodeStream(in);*/
try {
Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));
Bitmap bitmap =
MediaStore.Images.Media
.getBitmap(this.getContentResolver(), uri);
/*
InputStream stream =
getAssets().open(sharedPreferencesData.getStr(
"ThemeName"));
Drawable d = Drawable.createFromStream(stream, null);
URL url_value = new URL(sharedPreferencesData.getStr(
"ThemeName").trim());
Bitmap mIcon1 =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
*/
I tried multiple ways none is working. Either the bitmap is empty or I am getting the File not found exception and malformedException.
Please help with the same.
EDIT :
I get the follwing string from getURLForResource :
D/ImageUri: android.resource://com.dailyfaithapp.dailyfaith/drawable/theme0
I have created a class with themename,font etc... and i am setting values to the same like :
public void setThemes(){
Themes themes = new Themes();
themes.setId(1);
themes.setImage(Utils.getURLForResource(R.drawable.theme1,this));
themes.setFont("AlexBrush-Regular.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(2);
themes.setImage(Utils.getURLForResource(R.drawable.theme2,this));
themes.setFont("SkinnyJeans.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(3);
themes.setImage(Utils.getURLForResource(R.drawable.theme3,this));
themes.setFont("Roboto-Thin.ttf");
themesArrayList.add(themes);
themes = new Themes();
themes.setId(4);
themes.setImage(Utils.getURLForResource(R.drawable.theme4,this));
themes.setFont("Raleway-Light.ttf");
themesArrayList.add(themes);
}
you can uri to drawable
public static Drawable uriToDrawable(Uri uri) {
Drawable d = null;
try {
InputStream inputStream;
inputStream = G.context.getContentResolver().openInputStream(uri);
d = Drawable.createFromStream(inputStream, uri.toString());
} catch (FileNotFoundException e) {
d = G.context.getResources().getDrawable(R.drawable.ic_launcher_background);
}
return d;
}
OR do these:
save bitmap in app root and again read
private void saveBitmap(Bitmap bitmap){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/images
File directory = cw.getDir("images", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"bg.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {}
}
Read Bitmap
private Bitmap readBitmap(String path)
{
try {
File f=new File(path, "bg.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}

Set Image using getAbsolutePath()

I'm trying to use custom gallery and trying to get the selected images and would like to display it in listview
This is what I'm trying to do:
if (extras != null) {
for (int i = 0; i < fetchList.size(); i++) {
Bitmap originBitmap = null;
filepath = fetchList.get(i);
newStringList.add(filepath);
imgfilename = filepath.substring(filepath.lastIndexOf("/") + 1);
Uri selectedImage = Uri.fromFile(new File(filepath));
File myFile = new File(selectedImage.getPath());
myFile.getAbsolutePath();
Toast.makeText(MainActivity.this,myFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
listimage.setImageBitmap(myFile.getAbsolutePath());
myStringList.add(imgfilename);
arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.custom_textview, R.id.listtext,
myStringList);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
}
Now my question is how do I set the image to the image view using this path ?
If I use this listimage.setImageBitmap(myFile.getAbsolutePath()); I couldnt see the image.
Path I'm getting is : /storage/emulated/0/
Pls try this way,
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Hope this will help you.
Try this
private AQuery aq = new AQuery(activity);
File imgFile = new File(filepath);
aq.id(imageView).image(imgFile, false, 300, new BitmapAjaxCallback() {
#Override
public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
iv.setImageBitmap(bm);
}
});

Get last captured image?

I have an application, where you can take a picture about yourself (the app saves the image in a specified folder called "MyAppImage"), and I want to display the taken image in a second activity with a code, how to do this? I want to display it in a imageView in my SecondActivity, but I need a code that can get the last captured camera image from this folder, is there any way to do this?
Hope someone can guide me, how to do this, thanks!
After take photo:
MainActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = "yourPhotoName" + ".jpg"
filePath = "pathOfMyAppImageFolder" + fileName;
File destination = new File(filePath);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
intent.putExtra("filePath", filePath)
startActivity(intent);
}
});
AnotherActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
filePath = intent.getStringExtra("filePath");
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
Take the last photo of the folder:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<File> files = getListFiles(new File("MyAppImageFolderPath"));
File imgFile = files.get(files.size());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".jpg")){ //change to your image extension
inFiles.add(file);
}
}
}
return inFiles;
}
Once you takePhoto, save it into file.
Then call intent to start second activity and putExtraString with your image file path.
That is all.

Image is does not show in ImageView dynamically from sdcard

In My Code The image is not open in ImageView from sdcard i already checked the permissions in 'manifest.xml'.
Same if i try to open it using static name then it will showed by ImageView but not dynamically.
Main Activity
private OnClickListener OnCapture = new OnClickListener() {
#Override
public void onClick(View v) {
String time = mCamUtils.clickPicture();
nextActivity = new Intent(MainActivity.this,EffectActivity.class);
nextActivity.putExtra("ImageName", time);
startActivity(nextActivity);
finish();
}
};
EffectActivity
public class EffectActivity extends Activity {
Intent getActivity = null;
ImageView image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.effectactivity);
getActivity = getIntent();
String name = getActivity.getStringExtra("ImageName");
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
Toast.makeText(getApplicationContext(), path, Toast.LENGTH_LONG).show();
image = (ImageView) findViewById(R.id.imageView1);
File f = new File(path);
byte[] b = new byte[(int)f.length()];
if(f.exists())
{
try
{
if(f.exists())
{
FileInputStream ff = new FileInputStream(f);
ff.read(b);
Bitmap g = BitmapFactory.decodeFile(path);
image.setImageBitmap(g);
ff.close();
}
else
{
Toast.makeText(getApplicationContext(), "ELSE", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
}
}
}
}
I am trying to open image which i saved in before this activity and i catch the name of image here but that does not show the image.
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
In this line try changing "JPG" into "jpg".i think your file extension might be in lowercase letter and it might say f.exists false.
Hope it will help.
String fname = "Pic-" + System.currentTimeMillis() + ".png";
File image= new File(imagesFolder, fname);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
try this code

screen shot for the activity

i want to create a bitmap of whats being currently displayed of my app, one thing i went into is cant read FB buffer requires root, would like to know if it is possible to create a image file for the screen, please i want the help to code this, no 3rd party intents , thanks, answers would be much appreciated
From your Activity (pseudo-code):
Bitmap bm = Bitmap.create...
Canvas canvas = new Canvas(bm);
getWindow.getDecorView().draw(canvas);
You can use FFMPEG to capture the Screen
Try this.....
{
LinearLayout view = (LinearLayout) findViewById(R.id.imageLayout);
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
String dir="myimages";
Bitmap bm = v1.getDrawingCache();
saveBitmap(bm, dir, "capturedimage");
}
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
System.out.println("Image size : "+bitmap.getHeight());
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
System.out.println("After File Size : "+f.length());
fos.flush();
fos.close();
return name;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in saveBitmap: "+e.getMessage());
} finally {
}
return null;
}

Categories

Resources