Android Google Maps v2 load OverlayTile from image in assets - android

I need to get the file URL to an image that I store locally in my app. I don't care where I store the file locally, just somewhere in which I can get a URL to it. I have tried assets and resources with no luck.
What I am trying to do is override UrlTileProvider:
public class FileSystemTileProvider extends UrlTileProvider {
public FileSystemTileProvider(int width, int height, String assestsDirectory) {
super(width, height);
}
#Override
public URL getTileUrl(int x, int y, int z) {
String tile = "file://<somewhere>/background.png";
URL fileUrl = null;
try {
fileUrl = new URL(tile);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileUrl;
}
}
I need to return a URL for this to work. I have hardcoded a file url and it does work. However I need a way to get a URL for my background.png image. Is this possible?

The easiest way would probably be to include the file as an asset in the APK, then extract it to the app's private directory with an AssetManager. For example as explained in this answer, except using getFilesDir() instead of getExternalFilesDir() (or even easier, by creating the FileOutputStream object with openFileOutput()).
Another option (especially if you want/need to provide different background images for different display densities) is to include it as a drawable, then extract it with a similar method.
After you have done either of these (only once, say at the main activity's start-up) and saved the file with a known name, just create the URL to this file.
File backgroundFile = new File(getFilesDir(), fileName);
URL fileUrl = backgroundFile.toURI().toURL();

I don't think you can access it that way.
But you can instead implement directly TileProvider and write your own implementation of
public Tile getTile (int x, int y, int zoom) {
//get the drawable
...
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return Tile(WIDTH, HEIGHT, stream.toByteArray());
}
Get the drawable from the drawables folder with:
Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.background);
or from assets folder with:
InputStream ins = getAssets().open("background.jpg");
Drawable d = Drawable.createFromStream(ins, null);

Related

resourceID from image in assets subfolder only works for some files

I have an assets subfolder and images on it all png's some bigger, I'm writing a hybrid app from Angular so I pass via an interface the name of a file to pop it in an activity I pass only the name not the extession. It works for some files but not for others (a bigger one on my case) is there a reason for that???, I'm using this basic code below, the smaller file resID has a number for the bigger file it comes out as 0. The png with the problem does load on a basic page in angular, I want to pop a zoomer of that image. Probably I could place a copy in the Drawable res folder, but Angular needs it hanging from my assets.
image = (TouchImageView) findViewById(R.id.cur_img);
if( getIntent().hasExtra("imageResName") ) // set it to passed image
{ // a popup pass in the image
String curResName =getIntent().getExtras().getString("imageResName");
// gte the di from a drawble ..it wprks
int resID = getResources().getIdentifier(curResName , "drawable", getPackageName());
image.setImageResource(resID);
}
UPDATE: Yep that code will NOT work I could pull an SO answer where
I probably misunderstood it ... this is the mod'ed code that will work
if( getIntent().hasExtra("imageResName") ) // set it to passed image
{ // a popup pass in the image
String curResName =getIntent().getExtras().getString("imageResName");
Bitmap bitmap=null;
try
{ // for image in: /assets/imagenes/xxx.png
AssetManager assetManager = getApplicationContext().getAssets();
InputStream istr = assetManager.open("imagenes/" + curResName + ".png" );
bitmap = BitmapFactory.decodeStream(istr);
istr.close();
}
catch (Exception ex)
{
bitmap = null;
}
finally
{
image.setImageBitmap(bitmap);
}

Android - Getting, saving and retrieving images from URL

I have a database of recipes, each of which has an image.
The database can be updated from a JSON feed. I then need to retrieve any new images for a newly added recipe. I'm having issues getting an image from a URL, saving it and then updating a recipe with that image.
There are a lot of different answers on Stack Overflow and other sites. Often I can get to what I would expect to be a working point. Where images appear to be getting saved, and any debug print outs I add in show what I expect, but I cannot update my ImageView. By that I mean it remains blank.
I'm not sure if my issue is simply a poor attempt to update the ImageView, or a problem when saving the images. This code is a bit sloppy and inefficient at the moment. I've tried 10-15 variations on this from suggested other posts and have had no luck. Any help would be greatly appreciated.
Manifest
/* I have these two set (Not sure both are necessary) */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Main frontend class
/* Create databaseHelper */
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
/* ImageView to update image of */
ImageView foodpic = (ImageView)findViewById(R.id.foodpic);
/* Check if image is already available in drawable folder */
int resID = this.getResources().getIdentifier(filename, "drawable", "mypackage.name");
if (resID == 0) {
/* If not, call function to retrieve from external storage */
newPic = db.getOutputMediaFile(origFilename);
if(newPic.exists()) {
myBitmap = BitmapFactory.decodeFile(newPic.getAbsolutePath());
foodpic.setImageBitmap(myBitmap);
foodpic.invalidate(); /* Tried with and without this */
}
}
DatabaseHelper function to retrieve image saved from URL
public File getOutputMediaFile(String filename){
/* Dir I'm (attempting) to save and retrieve images from */
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/mypackage.name/Files");
/* Create the storage directory if it does not exist */
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/* Get file extension */
String[] fileNameSplit = filename.split("\\.");
String extension = fileNameSplit[(fileNameSplit.length-1)];
/* Get filename, remove special chars & make lowercase */
int extensionIndex = filename.lastIndexOf(".");
filename = filename.substring(0, extensionIndex);
filename = filename.toLowerCase(Locale.getDefault());
filename = filename.replaceAll("[^a-z0-9]", "");
/* Re-make filename to save image as */
String mImageName="r"+filename+"."+extension;
/* Get file
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
DatabaseHelper function to save image from URL
- Called per recipe/image added to the database, if image not found in drawable folder.
public static void saveImage(String imageUrl, String destinationFile, String extension) throws IOException {
URL url = new URL (imageUrl);
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,destinationFile));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
*Formatting.
Store URL as string in DB and display it with Image Loader is more easy, but doesn't work off line ,if ur apps need internet to work, the image loader could be better.
android-loading-image-from-url-http
I ended up using this library.
It's not an ideal solution as I'd have preferred to look through this library, understand it fully and explain it for others who may need a similar answer. But for now, people attempting to do something similar should be able to use this too.
https://code.google.com/p/imagemanager/

issues to save and retrieve the image in android?

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()

Android Show image by path

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

How to get access to raw resources that I put in res folder?

In J2ME, I've do this like that:
getClass().getResourceAsStream("/raw_resources.dat");
But in android, I always get null on this, why?
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
In some situations we have to get image from drawable or raw folder using image name instead if generated id
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Android access to raw resources
An advance approach is using Kotlin Extension function
fun Context.getRawInput(#RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(#RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout
hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
This worked for for me: getResources().openRawResource(R.raw.certificate)

Categories

Resources