I have a folder with a few images, these images are added by user dynamically. So i need to get the R.drawable ID's of these images in android.... ???
Where are you saving these images too? When images are being added dynamically at runtime usually you need to store them on the phones storage. If you want the images to be stored in the external storage (SDCard) then you can use the following code to retrieve them and add them to your view (Which I assume your doing). This code assumes the images are being stored to your devices SDCard, which is where they will be pulled from.
//Get root directory of storage directory, pass in the name of the Folder if they are being stored farther down, i.e getExternalFilesDir("FolderName/FolderName2")
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
File dir = getExternalFilesDir(null);
Bitmap bmap = null;
try {
InputStream is = new FileInputStream(new File(dir,"image.jpg"));
bmap = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (bmap!=null) {
ImageView view = new ImageView(this);
view.setImageBitmap(bmap);
}
}
Related
Im new to android development and trying to get metadata of image using ExifInterface. I stored the image under drawable and trying to get the metadata but getting null values for all fields(date, imagelength, imagewidth). I tried to access image path as this :
String path = "drawable://" + R.drawable.testimage;
and provided this path to ExifInterface.
ExifInterface exif = new ExifInterface(path);
I dont know if storing image under drawable is correct or not because when I run the app in emulator I get something like this :
E/JHEAD﹕ can't open 'drawable://2130837561'
So if this is wrong then please tell me where should I store the image and how to provide image path to ExifInterface.
Thank you in advance.
To get a drawable, you can you this snippet:
Drawable drawable = getResources().getDrawable(android.R.drawable.your_drawable);
I'm not sure if your way is correct, as I've never seen it like that. Do you really need the path to your image to use it on that ExifInterface class?
Ok, I did some digging and found this question, which led me to this one. As it seems, you can not get an absolute path from a resource inside your apk. A good solution would be for you to save it as a file on the external memory, and then you can get the path you want.
First of all, add this to your AndroidManifest.xml, so your app can write to the cellphone memory:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok, to save it you can try this, first create a bitmap from your drawable resource:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.your_drawable);
After that get the path you want to save your images, and put it on a String. More info on that here.
The Android docs have a good example on how to get the path. You can see it here.
To keep it simple, I'll copy and paste the snippet from the docs.
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// 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(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
return file.exists();
}
return false;
}
After that, get the path of the file you saved on the external memory, and do as you wish.
I'll keep the old example as well. You can use the method getExternalStorageDirectory() to get the path, or getExternalCacheDir(). After that, you can use File method called getAbsolutePath() to get your String.
String path = (...) // (you can choose where to save here.)
File file = new File(path, "your_drawable.png");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // You can change the quality from 0 to 100 here, and the format of the file. It can be PNG, JPEG or WEBP.
out.flush();
out.close();
For more info on the Bitmap class, check the docs.
If you need more info, let me know and I'll try to show more samples.
EDIT: I saw your link, and there was this snippet there:
//change with the filename & location of your photo file
String filename = "/sdcard/DSC_3509.JPG";
try {
ExifInterface exif = new ExifInterface(filename);
ShowExif(exif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Error!",
Toast.LENGTH_LONG).show();
}
As you can see, if you really want to see the exif data of a internal image resource, you'll have to save it somewhere else, and then you can try to get the absolute path for that File, then, call the method to show the exif.
I'm new in Android development and I have an app that saves a 'jogador' (player) record with some attributes (name, birthday...) and a photo.
When the user picks the image from gallery, I populate an ImageView with the photo so that the user can see it before he saves the record. (It's working here).
My problem is that I want to save that photo in a folder created by me (Inside res/ folder). eg: res/myFolder.
I don't know how I will access that folder to put an image inside. Follow my code bellow:
Bitmap bmp = BitmapFactory.decodeFile(fotoPath); //---> It works
FileOutputStream fos;
try {
// 'fotos_jogador' is my folder inside res folder.
// I think that 'Environment.getExternalStorageDirectory()'
// gives me access to sdcard, but i don't want this, I want to save in a local app folder.
File file = new File(Environment.getExternalStorageDirectory() +
File.separator + "/fotos_jogador/" + ".png");
fos = new FileOutputStream(file);
//I want do store a low quality image, just for contact photo.
if(fos != null){
bmp.compress(CompressFormat.PNG, 20, fos);
fos.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Then, guys, my doubts:
How can I give a custom name for my Image?
How can I Save the image in my folder 'fotos_jogador'?
How can I retrieve the Image after it's saved?
I appreciate the help. Thanks!
no you can not save anything in resource folder here is the link of duplicate post Is it possible to save image in assets folder from application
you can save image in sd card or in internal memory.
How to compare one image token with camera with all the other images stored in the sd card and display the result?
public class SearchForFaces extends Activity {
Bitmap bitmapOriginale;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b1 = getIntent().getExtras();
String cin= b1.getString("cin");
//getting the image
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Student");
File file = new File(directory, cin+"jpg");
try {
FileInputStream streamIn = new FileInputStream(file);
bitmapOriginale = BitmapFactory.decodeStream(streamIn);
streamIn.close();
} catch (IOException e) {
Log.d("SearchForFaces Exception", e.getMessage());
}
if(bitmapOriginale.sameAs(//images from sdcard))
{
//display founded image
}
}
}
i think, its not necessary read all images..if you want compare images from camera, you can "easy" take the images in DCMI folder. But ok, user will move some files in another folder. So in that case i will advice just open first folder, read files in there and check the format, after that open another folder, read files in there and again check the formats and save the paths to the jpg files.
So in this case just easy some for, foreach, while cykl or you can do it with recursion.
You will have some ArrayList (linkedList, whatever) and in this list you can put the paths. Then just call your sameAs method.
On this you can use Environment.getExternalStorageDirectory().listFiles();
But..i am not sure if your "algorithm" will work..image recognition is really hard part of computer science..and if you dont know how to get the files on SDcard..the algorithm wouldnt probably work..
But if you want to check the similarity with byte by byte comparsion, then its ok..
Check also this blog http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html It shows how to read an images from sd card. Once you read them you can use your sameAs() written method to compare them.
I have an application that uses a canvas function, I want to save and retrieve all images (whatever I saved).?
issues
I can save and retrieve the single image only
Dynamically I save the image,(image001,image002......)
update
try {
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/image00"+saveimageid+".jpg")));
saveimageid++;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I retrieve the image from image001.
File imgFile = new File("/mnt/sdcard/image001.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.ImageView01);
myImage.setImageBitmap(myBitmap);
I'm guessing you want to load all the files that match imageXYZ.jpg.
I have no idea why you save the files like "00"+saveimageid+".jpg.
If you want to make sure the filename is equally long (or at least three positions) do something like
new File(String.format("/mnt/sdcard/image%03d.jpg", saveimageId))
To retrieve the files you might
File dir = new File("/mnt/sdcard/");
File[] images = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(final File dir, final String filename) {
return filename.matches("image[0-9]+\\.jpg");
}
});
Then you can use the images array however you please.
As a sidenote: If this is Android you should not assume that external storage is placed in /mnt/sdcard. Use Environment.getExternalStorageDirectory()
i want to show image in imageview without using id.
i will place all images in raw folder and open
try {
String ss = "res/raw/images/inrax/3150-MCM.jpg";
in = new FileInputStream(ss);
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
but this is not working i want to access image using its path not by name
read a stream of bytes using openRawResource()
some thing like this should work
InputStream is = context.getResources().openRawResource(R.raw.urfilename);
Check this link
http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode
It clearly says the following
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID
If you want to give a file name like the one mentioned in ur code probably you need to save it on assets folder.
You might be able to use Resources.getIdentifier(name, type, package) with raw files. This'll get the id for you and then you can just continue with setImageResource(id) or whatever.
int id = getResources().getIdentifier("3150-MCM", "raw", getPackageName());
if (id != 0) //if it's zero then its not valid
image.setImageResource(id);
is what you want? It might not like the multiple folders though, but worth a try.
try {
// Get reference to AssetManager
AssetManager mngr = getAssets();
// Create an input stream to read from the asset folder
InputStream ins = mngr.open(imdir);
// Convert the input stream into a bitmap
img = BitmapFactory.decodeStream(ins);
} catch (final IOException e) {
e.printStackTrace();
}
here image directory is path of assets
like
assest -> image -> somefolder -> some.jpg
then path will be
image/somefolder/some.jpg
now no need of resource id for image , you can populate image on runtime using this