Load Images from Assets in Widget remoteView - android

I am using the following code to load my image into Android widget ImageView:
remoteViews.setImageViewResource(R.id.widget_image, R.drawable.image);
I have to save the image in drawable folder. Is it possible to save the image in assets instead and load it to remoteView?

Using BitmapFactory, you can load an image in assets/ as a Bitmap from an InputStream provided by AssetManager, and then use the RemoteViews#setImageViewBitmap() method to set it on your widget.
For example:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
...
try {
InputStream is = context.getAssets().open("image.jpg");
Bitmap bmp = BitmapFactory.decodeStream(is);
remoteViews.setImageViewBitmap(R.id.widget_image, bmp);
}
catch (IOException e) {
e.printStackTrace();
}

Here is the solution :
imageView = (ImageView)findViewById(R.id.iv);
try {
// get input stream
InputStream ims = getAssets().open("download.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
}
catch(IOException ex) {
return;
}

Related

Adding images from assets folder in adapter

I'm trying to display images from assets folder. I have this error:
Bitmap bitmap = getBitmapFormatAssets(product.getProductId());
try { Bitmap bitmap = getBitmap(product.getProductId()); imageView.setImageResource(bitmap);
It must be setImageBitmap(bitmap) not setImageResource(bitmap)
Instead of imageView.setImageResource(bitmap) try to use imageView.setImageBitmap(bitmap) directly.
when you want to set a bitmap image to a image view don't use setImageResource(bitmap)
use setImageBitmap(bitmap) as below
setImageBitmap(bitmap) Sets a Bitmap as the content of this ImageView.
like this
imageView.setImageBitmap(bitmap)
get your bitmap from assets using below code
private Bitmap getBitmapFromAsset(String strName)
{
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open(strName);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
following are used for getting the image from asset folder and set it to ImageView.
// load image
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) {
return;
}

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.

Android : cannot read image in assets folder and assign to imageview

I have a file food.jpg in assets folder. I have try many ways. but I still cannot get this image into imageView. when run, instead of display image "food.jpg", it displays image that I have declared in xml file. (that image is in drawable folder).
The first way is:
int asset_id = context.getResources().getIdentifier("food", "drawable", context.getPackageName());
imageView.setImageResource(asset_id);
The second way is:
AssetManager assetManager = context.getAssets();
InputStream istr;
try {
istr = assetManager.open("food");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Please teach me how to fix this problem.
thanks :)
Your code is working fine. just add image MIME-Type(.jpg,jpeg,.png... etc) in below line:
istr = assetManager.open("ceo.jpg");
full code for your refrance
AssetManager assetManager = getAssets();
InputStream istr;
try {
istr = assetManager.open("ceo.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Try this Code...
try {
// get input stream
InputStream ims = getAssets().open("food.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imgNews.setImageDrawable(d);
} catch (Exception ex) {
return;
}
}

How can I write a Drawable resource to a File?

I need to export some Drawable resources to a file.
For example, I have a function that returns to me a Drawable object. I want to write it out to a file in /sdcard/drawable/newfile.png. How can i do it?
Although the best answer here have a nice approach. It's link only. Here's how you can do the steps:
Convert Drawable to Bitmap
You can do that in at least two different ways, depending on where you're getting the Drawable from.
Drawable is on res/drawable folders.
Say you want to use a Drawable that is on your drawable folders. You can use the BitmapFactory#decodeResource approach. Example below.
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
You have a PictureDrawable object.
If you're getting a PictureDrawable from somewhere else "at runtime", you can use the Bitmap#createBitmap approach to create your Bitmap. Like the example below.
public Bitmap drawableToBitmap(PictureDrawable pd) {
Bitmap bm = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
canvas.drawPicture(pd.getPicture());
return bm;
}
Save the Bitmap to disk
Once you have your Bitmap object, you can save it to the permanent storage. You'll just have to choose the file format (JPEG, PNG or WEBP).
/**
* #param dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir() depending on where you want to save the image.
* #param fileName The file name.
* #param bm The Bitmap you want to save.
* #param format Bitmap.CompressFormat can be PNG,JPEG or WEBP.
* #param quality quality goes from 1 to 100. (Percentage).
* #return true if the Bitmap was saved successfully, false otherwise.
*/
boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir,fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format,quality,fos);
fos.close();
return true;
}
catch (IOException e) {
Log.e("app",e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
And to get the target directory, try something like:
File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "drawable");
boolean doSave = true;
if (!dir.exists()) {
doSave = dir.mkdirs();
}
if (doSave) {
saveBitmapToFile(dir,"theNameYouWant.png",bm,Bitmap.CompressFormat.PNG,100);
}
else {
Log.e("app","Couldn't create target directory.");
}
Obs: Remember to do this kind of work on a background Thread if you're dealing with large images, or many images, because it can take some time to finish and might block your UI, making your app unresponsive.
get the image stored in sdcard..
File imgFile = new File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Update:
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);

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.

Categories

Resources