Retrieve image path from assets folder - android

I have issue to retrieve image path from assets folder.
I have an image folder in assets folder. Within the folder i have three different folders.
Here is the code that i used:
String IntroImage1= "" + languageSelected + "/" + Intro1ImagePath + ".png" ;
try{
AssetManager mngr =getAssets();
InputStream BulletImgInput = mngr.open(IntroImage1);
//InputStream BulletImgInput = mngr.open("image/Malay/bullet.png");
Bitmap bitmapBullet = BitmapFactory.decodeStream(BulletImgInput);
BulletImage.setImageBitmap(bitmapBullet);
}catch(final IOException e){
e.printStackTrace();
}
I am wondering why can't i display the image? Because I have try to retrieve it through this code:
InputStream BulletImgInput = mngr.open("image/Malay/bullet.png");
It did retrieve the file, but with the string that i replaced in mngr.open it doesn't show up.
Really need you guys to help up.Thanks.

You don't need the AssetManager. You can do
BitmapFactory.decodeFile("file:///android_asset/image/Malay/bullet.jpg")
Though storing Images in the Assets is not the best way to go. You will not be able to take advantage of the Android resource management system. So unless you have a compelling reason to do this, I'd suggest that you take a look at using the res folder and the resources system.
Update: Explanation
The BitmapFactory has a method to decode a file via the decodeFile method. That's point one. Android lets you access a file in the assets folder via the file:///android_asset/{path} path. In your case, the Image at /image/Malay/bullet.jpg is the assets folder can be accessed via the the file:///android_asset/image/Malay/bullet.jpg.

Try this:
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
Log.e("I/O ERROR","Failed when ..."
}
your BulletImage

String url = "file:///android_asset/NewFile.txt";
String url = "file:///android_asset/logo.png";
you can access any file....

InputStream BulletImgInput = mngr.open("file:///android_asset/image/Malay/bullet.png");
Maybe this could work for u.

May be problem is in missed image part of path?
String IntroImage1= "image/" + languageSelected + "/" + Intro1ImagePath + ".png" ;
instead of
String IntroImage1= "" + languageSelected + "/" + Intro1ImagePath + ".png" ;
Upd: Check values of languageSelected and Intro1ImagePath also.

Related

How to get path of any file from my my application data folder

My application files are bellow, I want to get sharethis.png file in java code , What is syntax ?
I used this ...
Bitmap bMap = BitmapFactory.decodeFile("file:///android_asset/www/sharethis.png");
but not working
Try:
Bitmap shareThis = BitmapFactory.decodeResource(context.getResources(),
R.drawable.shareThis);
If you want to reference it from a JavaScript or html file in your assets folder, use file:///android_asset/www/sharethis.jpg.
Otherwise, according to this answer, this will list all the files in the assets folder:
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
This to open a certain file:
InputStream input = assetManager.open(assetName);
Try this:
try {
// get input stream
InputStream ims = getAssets().open("sharethis.png");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
Log.e("I/O ERROR","Failed")
}
Instead of using the assets dir, put the file into /res/raw , and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.sharethis

android-where to store lots of images and how to move them while installing

I'm writing an android app that contains about 500 images .
there are somethings that make me worry, I don't want to use internet.
1-the application size will be very big , is there anyway to moving images to sd card while installing? some devices may don't have this amount of space on the phone .
2-should I make 3 images for hdpi , ldpi and mdpi ?
You can put you image in asset folder. If you want to transfer image from assets to SD Card then you can't do like this.
But you can do by one way. You put your image on server and at 1st time when you will open app you can download it and save it in SD Card and then access from there.
Yes, it will be big. No, you can't remove them from your package.
No, you can make only hdpi images. Android will scale them automatically (which may slow down a bit the app).
Suggestion - use internet. Since the user has internet to download your app, he can wait to download the resources on first start. Also it give you the ability to add/remove files via online configuration. Just imagine if you have to add 1 image and upload new version - this means that the user will have to download the same huge package again.
I had a similar requirement - include a bunch of images in the app, but in my case, the image had to be accessible by any user or app, not just the app that unpacked them. I stored them in the res/raw folder and copied them to user space on start up:
private void loadCopyResources() {
// copy resources to space any activity can use
String sourceName;
String resourceName;
String fileName;
int resource;
String typeName = sourceSink.Types.photo.toString();
for (sourceSink.Sources source: sourceSink.Sources.values() ){
for (int i = 0; i< photoFileCount; i++) {
sourceName = source.toString();
resourceName = sourceName + "_" + typeName + (i+1); // i.e. dropbox_photo2
fileName = resourceName + ".jpg"; // files requires extension
resource = getResources().getIdentifier(resourceName, "raw", "com.example.myapp");
createExternalStoragePublicFile(typeName,fileName, resource); // copy it over
}
}
}
void createExternalStoragePublicFile(String fType, String fname, int res ) {
// Create a path where we will place our picture in the user's
// public pictures directory. Note that you should be careful about
// what you place here, since the user often manages these files. For
// pictures and other media owned by the application, consider
// Context.getExternalMediaDir().
File path = null;
if (((fType.equals(sourceSink.Types.photo.toString())) || (fType.equals(sourceSink.Types.file.toString())) ) ){
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
}
if (fType.equals(sourceSink.Types.music.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
}
if (fType.equals(sourceSink.Types.video.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
}
File file = new File(path, "/" + fname);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(res);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
scanMedia(file);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
sourceSink, which I didn't include, is just a list of file names and file types I needed copied.

AssetManager and InputStream for ImageView

This is the part of my function that assigns an image to my ImageView. I can not get it to show an image. I have my files listed under assets/signs/"image names." This code came straight from my textbook with some minor tweaks to fit my code. I appreciate the help.
String nextImage = signNames.remove(0);
AssetManager assets = getAssets();
InputStream stream;
try{
stream = assets.open("signs/"+nextImage + ".gif");
Drawable sign = Drawable.createFromStream(stream,nextImage +".gif" );
signImageView.setImageDrawable(sign);
}
catch(IOException e){
Log.e(TAG, "Error loading " +nextImage, e);
}
I think there is a much simpler idiom for what you are trying to do. No need to stream the image the want to display. Simply put the image in res/drawable (or res/drawable-hdpi, etc). Then simply:
signImageView.setImageResource(R.drawable.myImage)
Of if you need to get the resource from a dynamic string:
int id = getResources().getIdentifier("yourpackagename:drawable/" + nextImage, null, null);
signImageView.setImageResource(R.drawable.myImage)
see here
This assumes your signImageView is indeed an ImageView.

Get object File from a file in raw folder

What i want to do is very simple :
String dataDir = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).applicationInfo.dataDir;
Log.e(TAG , "dataDir = " + dataDir);
File tmpFile = new File(dataDir + "/raw/ocr.jpg");
But i got a file not found exception
i NEED an object file as after i do
photoUriString = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), tmpFile.getAbsolutePath(), null, null);
(because i want to share the picture on google+, see How to share image in google Plus through an android app?)
So please don't tell me about a reader, a bufferedReader, etc ...
Thanks
InputStream is = getResources().openRawResource(R.raw.ocr.jpg));
you have to get the InputStream through openRawResource, then you can manage it as you need

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