NinePatchDrawable from Drawable.createFromPath or FileInputStream - android

I cannot get a nine patch drawable to work (i.e. it is stretching the nine patch image) when loading from either Drawable.createFromPath or from a number of other methods using an InputStream.
Loading the same nine patch works fine when loading from when resources. Here's the methods I am trying:
Button b = (Button) findViewById(R.id.Button01);
Drawable d = null;
//From Resources (WORKS!)
d = getResources().getDrawable(R.drawable.test);
//From Raw Resources (Doesn't Work)
InputStream is = getResources().openRawResource(R.raw.test);
d = Drawable.createFromStream(is, null);
//From Assets (Doesn't Work)
try {
InputStream is = getResources().getAssets().open("test.9.png");
d = Drawable.createFromStream(is, null);
} catch (Exception e) {e.printStackTrace();}
//From FileInputStream (Doesn't Work)
try {
FileInputStream is = openFileInput("test.9.png");
d = Drawable.createFromStream(is, null);
} catch (Exception e) {e.printStackTrace();}
//From File path (Doesn't Work)
d = Drawable.createFromPath(getFilesDir() + "/test.9.png");
if (d != null) b.setBackgroundDrawable(d);

I answered a very similar question here about non-resource-based ninepatches. To read a file from within .apk archives, I use something like this:
String filepath = "com/kanzure/images/thx1138.png";
InputStream stream = getClass().getClassLoader().getResourceAsStream(filepath);

I have a very similar problem. I'm trying to create a NinePatchDrawable from a Bitmap that I've retrieved over the network. I still haven't found a solution to that problem. Since the Drawable.createFrom... methods apparently doesn't work, my only option seems to be to understand how to format the nine-patch chunk, and to invoke the NinePatch constructor. See the SO-thread for details.

Related

Display image button from external source

I'm working on a project where I need to display image buttons with some images saved in the sd card or from an Url. How can I do this? Or what's best practice?
The objective is to change the image on the button only replacing the file in the sd card.
There are other solutions if I don't know which images will be displayed in future?
THX
Here is how to load an image from a URL into a Drawable object:
InputStream is = (InputStream) new URL("http://my.url/path/to/image").getContent();
Drawable buttonBg = Drawable.createFromStream(is, null);
Then set it as the background:
button.setBackgroundDrawable(buttonBg);
or for API 16+ use:
button.setBackground(buttonBg);
If you want to read from a file, use a FileInputStream like so:
FileInputStream fis = openFileInput("/my/path/to/image");
Drawable buttonBg= Drawable.createFromStream(fis, null);
#carmex
Solved:
ImageButton box1 = (ImageButton)findViewById(R.id.box1);
Drawable drawable = GetImg("path/to/image.jpg");
box1.setBackground(drawable);
private Drawable GetImg(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
System.out.println("Err="+e); return null;
}
}
Thx a lot.

ListView lags when loading from application cache

I wrote a little piece of code that download image from internet and cache them into cache dir.
It runs in a secondary thread.
{
String hash = md5(urlString);
File f = new File(m_cacheDir, hash);
if (f.exists())
{
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
return d;
}
try {
InputStream is = download(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
if (drawable != null)
{
FileOutputStream out = new FileOutputStream(f);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
bitmap.compress(CompressFormat.JPEG, 90, out);
}
return drawable;
} catch (Throwable e) { }
return null;
}
I use this code to load picture inside a ListView item, and it works fine. If I remove the first if (where i load image from disk) it runs smoothly (and download picture every time!). If I keep it, when you scroll listview you feel some lags during picture's loading from disk, why?
To answer the question "why", I experienced this with lots of gc() messages in my logcat. Android allocates the memory before decoding the file from disk which could cause garbage collection, which is painful for the performance in all threads. Probably the same happens when you encode your jpeg as well.
For decoding part you can try reuse existing bitmap if you have one to let Android decode image in-place. Please have a look at the following snippet:
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
options.inMutable = true;
if (oldBitmap != null) {
options.inBitmap = oldBitmap;
}
return BitmapFactory.decodeFile(f.getAbsolutePath(), options);
http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
Do in background.( use AsyncTask to load images.)

Loading images from cache but return a blank screen

i try the example i gotten from here. The example shows how to display a image that is larger then the screen and the screen acting like a window, allowing user to look at the images via scrolling. However, what i want to achieved is similar just that, instead of one single image, i tried to combining 18 smaller images (171X205) into one single image. I am able to did that but to save loading time on downloading of images from the server, i cached the images. Heres the problem, i cant seems to display the images out on screen even though the images are indeed cached. Thus, i tried something else by fetching image from the drawable folder but still the same issue arise. Does anyone have any idea how to go about solving this problem?
A snippets of code to load images from cache:
for(int i =0; i<18; i++)
File cacheMap = new File(context.getCacheDir(), smallMapImageNames.get(i).toString());
if(cacheMap.exists()){
//retrieved from cached
try {
FileInputStream fis = new FileInputStream(cacheMap);
Bitmap bitmap = BitmapFactory.decodeStream(fis)
puzzle.add(bitmap);
}catch(...){}
}else{
Drawable smallMap = LoadImageFromWebOperations(mapPiecesURL.get(i).toString());
if(i==0){
height1 = smallMap.getIntrinsicHeight();
width1 = smallMap.getIntrinsicWidth();
}
if (smallMap instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable)smallMap).getBitmap();
FileOutputStream fos = null;
try {
cacheMap.createNewFile();
fos = new FileOutputStream(cacheMap);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
puzzle.add(bitmap);
}
}
}
The function where it retrieved images from the server
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
I am drawing onto a canvas and so no ImageView is use to display the images.
For all of my lazy image loading I use Prime.

Android - How to download an image and use it at run time?

Im my app when the splash screen gets started I am just hitting an URL and getting back an XML file. From that XML file i am parsing out data such as an user name, id and an URL to download an image. From that url i want to download an image and i want to store the image in a particular name in my app itself.I want to use the same image as a background in another activity. How can i download and store the image in my app. Where can it be stored in my app, either in raw folder or in drawable.
Before storing the name how come the image can be set as a background image in the particular activity, Please help me friends
This is the code to download your image from an url :
InputStream in = new URL(image_url).openConnection().getInputStream();
Bitmap bm = BitmapFactory.decodeStream(in);
Note that it should be done asynchronously (like in an asynctask)
Than you can store the Bitmap on the system using:
File fullCacheDir = new File(Environment.getExternalStorageDirectory(),cacheDir);
String fileLocalName = name+".JPEG";
File fileUri = new File(fullCacheDir, fileLocalName);
FileOutputStream outStream = null;
outStream = new FileOutputStream(fileUri);
image.compress(Bitmap.CompressFormat.JPEG, 75, outStream);
outStream.flush();
Note that this is just an example on how to store your image and there is other ways. You should look at documentation anyway.
If you want it for your application. Better download the image save it as Drawable instance and use it in your application where you want
public static Drawable drawable = null;
//get image from URL and store it in Drawable instance
public void getImageFromURL(final String urlString) {
Thread thread = new Thread() {
#Override
public void run() {
//TODO : set imageView to a "pending" image
InputStream is = null;
try{
URLConnection urlConn = new URL(urlString).openConnection();
is= urlConn.getInputStream();
}catch(Exception ex){}
drawable = Drawable.createFromStream(is, "src");
}
};
thread.start();
}
set Background image to any view
void setImage(View myView){
myView.setBackgroundDrawable(drawable);
}

How to set an image in an image view, android

Hi I want to show an image from SD card. I have 10 images. out of which i am able to show 9 images but 1 image i cannot show in image view.
My SD card location is correct. I am using android programming. I am getting file exists as true. also I am getting not null input stream but when I want to get Drawable object for some fiels i am not getting but for all others getting drawable object.
Also I have tried using
iv1.setImageURI(Uri.parse(str1))
but i didnot get any solution
Following is my code snippet
InputStream is1 = getBitMapImage(str1);
InputStream is2 = getBitMapImage(str2);
InputStream is3 = getBitMapImage(str3);
Drawable d1 = Drawable.createFromStream(is1, "first");
Drawable d2 = Drawable.createFromStream(is2, "second");
Drawable d3 = Drawable.createFromStream(is3, "third");
iv1.setImageDrawable(d1);
iv2.setImageDrawable(d2);
iv3.setImageDrawable(d3);
System.out.println(is1+"....d1...."+d1);
System.out.println(is2+"....d2...."+d2);
System.out.println(is3+"....d3...."+d3);
public static BufferedInputStream getBitMapImage(String filePath) {
Log.e("Utilities", "Original path of image from Utilities "+filePath);
File imageFile = null;
FileInputStream fileInputStream = null;
BufferedInputStream buf= null;
try{
imageFile= new File(filePath);
System.out.println("Does Images File exist ..."+imageFile.exists());
fileInputStream = new FileInputStream(filePath);
buf = new BufferedInputStream(fileInputStream);
}catch(Exception ex){
}finally{
try{
imageFile = null;
fileInputStream.reset();
fileInputStream.close();
}catch(Exception ex){}
}
return buf;
}
Some image files cannot be shared. Blackbery rem file cannot be shared. That type of file cannot be opened if stored directly. So during storing convert that file into .jpg file and then only u can open those file. For checking purpose pullout your file from the device to your system then convert in into .jpg file using gimp and push into device once again then try to run your program and check whether your image file is diplayed in your image view.
Thanks
Sunil

Categories

Resources