Populate Android Gallery from image file paths? - android

I have some images that are saved to a directory on the Android device when the application starts--I would like to be able to display these images in a Gallery, but so far I haven't been able to do it.
I was following the sample Gallery code here, but it uses drawable resource IDs instead of file paths. I found this solution that is similar to what I'm looking for, except it uses ImageView instead of Gallery.
So the code using ImageView would look something like this:
File imgFile = new File(“/data/data/com.myproject.example/files/someImage.png”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
The above code works, but I'm not sure how to do it with a Gallery. I have been searching for answers and trying different things, but I'm v new to Android development and I feel like I'm in a bit over my head.
Any help is appreciated. Thank you in advance.

Basically I think you just need to put your two examples together.
Use the HelloGallery example as a start, however you want to change the code inside the getView() method of the ImageAdapter to call setImageBitmap() on the ImageView instead of setImageResource().
You will need an array/collection of file paths of images you want to load.

What you need to do is something like this:
public ImageAdapter(Context c, int itemId) {
context = c;
imgArr = GlobalStore.getItem(itemId).getPhotos();
TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
attr.recycle();
}
as you can see this is basically a copy from Gallery tutorial. In the constructor imgArr variable is loaded with an array of JPG file names. These were for example read from a database.
Then in the getView function you have something like this...
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
String tmpStr = appContext.getFilesDir() + File.separator + "photos" + File.separator + imgArr.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(tmpStr);
imageView.setImageBitmap(bitmap);
imageView.setLayoutParams(new Gallery.LayoutParams(350, 300));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
As you can see getFilesDir() gets your applications data location where it stores files, then let's imagine all photos are in "photos" directory, you build a path and attach a file name from the imgArr array. Since this is called for every photo you just use the passed position variable.
If you don't have an array of photos then maybe the way is to build it by reading the directory where you store photos, load all of the filenames in an array and then do this.
Then you do the rest on the gallery side as in the gallery tutorial.

Related

Save RelativeLayout with content as an image

I have relativelayout (A template) where it contain textboxes whose content is populated at runtime.On clicking save button,I need to save the template as an image in SD card.Is it possible.
I referred the below link:
How do I convert a RelativeLayout with an Imageview and TextView to a PNG image?
But the image saved cannot be opened.
Is my requiremnet possible.Or else please advice how can I achieve it.
I am behind this for several days.I am new to ANdroid.Please help.
Thanks in Advance.
You can pass any view or layout to devBitmapFrmViewFnc function and get the bitmap. You can save the bitmap in jpeg using devImjFylFnc.
|==| Dev Bitmap Image from View :
Bitmap devBitmapFrmViewFnc(View viewVar)
{
viewVar.setDrawingCacheEnabled(true);
viewVar.buildDrawingCache();
return viewVar.getDrawingCache();
}
|==| Create a JPG File from Bitmap :
static void devImjFylFnc(String MobUrlVar, Bitmap BitmapVar)
{
try
{
FileOutputStream FylVar = new FileOutputStream(MobUrlVar);
BitmapVar.compress(Bitmap.CompressFormat.JPEG, 100, FylVar);
FylVar.close();
}
catch (Exception ErrVar) { ErrVar.printStackTrace(); }
}

Read and load images from SDcard asynchronously - fail

I'd like to load image which is on SDCARD in folder to imageView of my cell in listView. I've tried different solutions but each of them fails. When I load images normally as it is in every base tutorial everything works. I've observed that, my application slows down when it has to load many images. Images are taken from photo camera of device. I'd like to load each of them asynchronously to avoid UI slow reaction. I've tried to use Thread, Asynctask but each of them throws error: "Only the oryginal thread that created a view hierarchy can touch its views". How to load images to avoid speed problems? SDImageLoader is a class which is possible to get from GITHUB. What I've tried is a standard code but is slows:
In a getView method in ListAdapter:
File imageFile = new File(Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png");
String imageFileString = Options.PATH_TO_FOLDER_PHOTOS_OF_APP + "test.png";
// "test.png" is a test file. Each cell will have different name of file to load.
if(imageFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
// final SDImageLoader loader = new SDImageLoader(context);
// new SDImageLoader().load(imageFileString, image);
//UrlImageViewHelper.setUrlDrawable(image, url);
}
else
{
final SDImageLoader loader = new SDImageLoader();
Resources resources = context.getResources();
int resurceId;
resurceId = resources.getIdentifier("bad", "drawable",context.getPackageName());
loader.load(imageFileString, image);
image.setImageResource(resurceId);
}
Have you tried to refresh your project after adding an external library to your project? It doesn't matter with the fragment. You send exact context to the List Adapter - which should be fragment.this.getActivity().

Getting path of local image instead of URL Android

I am working with gif images at the moment and have followed the answer from the question here
From this I have the following line of code:
GifWebView view = new GifWebView(this, "http://cdn.lifebuzz.com/images/17487/lifebuzz-35df9a5ee351ae72711e5a293658e319-limit_2000.gif");
Now, I want to download this image, save it locally in the "drawable" folder or "assets" folder and then access it from there.
I have tried downloading the image into the "drawable" folder and trying :
GifWebView view = new GifWebView(this, "#drawable/myimg.gif");
I have also tried this:
int imageResource = R.drawable.myimg;
Drawable image = getResources().getDrawable(imageResource);
String imageUri = "drawable://" + R.drawable.myimg;
GifWebView view = new GifWebView(this, imageUri);
Still no luck.
I've tried accessing it from the assets folder but this seemed even more complicated.
I just would like to save it locally and access it locally, I don't really care where it is stored.
Thanks for any help.
EDIT
public GifWebView(Context context, String path) {
super(context);
loadUrl(path);
}

How to refresh current picture from Gallery android

After searching an trying how to do it, I put this question due to my failures.
The point is I am trying to show in a Gallery several pictures that I get from a http server. The thing is when I open the activity for first time, if the picture is not in a specific folder, local cache, I display a default picture and them I launch a download of the picture by a AsyncTask. What I try is as soon as the picture has been downloaded and save in the folder, to update/refresh the gallery in the activity to display the picture. If I slip left/right the gallery the picture appear when the gallery is refresh, but I want this happen avoiding to slip the gallery.
Also comment that the base adapter is all the time with the right reference to the picture, the default picture is selected if the file does not exist in the folder.
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageBitmap(getPicturePath(position + 1));
i.setLayoutParams(new Gallery.LayoutParams(wHeight / 3, wHeight / 4));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
private Bitmap getPicturePath(int picture) {
String picturePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/pictures/" + picture
+ ".jpg";
File f = new File(picturePath);
if (f.exists())
return BitmapFactory.decodeFile(picturePath);
else
return BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.no_image);
}
I try to invalidate() in the gallery and also notifyDataSetChanged() in the adapter, baseadapter, but it does not work, the pictures on the screen do not change.
Any suggestion how to solve this?
Many thanks.

Android get image path from drawable as string

Is there any way that I can get the image path from drawable folder in android as String. I need this because I implement my own viewflow where I'm showing the images by using their path on sd card, but I want to show a default image when there is no image to show.
Any ideas how to do that?
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
based on the some of above replies i improvised it a bit
create this method and call it by passing your resource
Reusable Method
public String getURLForResource (int resourceId) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
Sample call
getURLForResource(R.drawable.personIcon)
complete example of loading image
String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
Glide.with(patientProfileImageView.getContext())
.load(imageUrl)
.into(patientProfileImageView);
you can move the function getURLForResource to a Util file and make it static so it can be reused
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
I think you cannot get it as String but you can get it as int by get resource id:
int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder
Sample Code
File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
if(!imageFile.exists()){//file doesnot exist in SDCard
imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
}

Categories

Resources