I am using the following method to pull a PNG file from the assets folder in my Android application:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
I am then setting the source of an ImageView, in the item of a GridView, to that Bitmap.
Here is the layout XML in question:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/containingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:background="#android:color/transparent"
android:padding="0dp"
android:layout_margin="0dp"
>
<ImageView
android:id="#+id/ivPackageIcon"
style="#style/smLargeGridItemPackageIconStyle"
/>
</LinearLayout>
And the style referred to in that XML is:
<style name="smLargeGridItemPackageIconStyle">
<item name="android:scaleType">fitXY</item>
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">142dp</item>
<item name="android:layout_margin">5dp</item>
<item name="android:background">#android:color/transparent</item>
</style>
Here is the code that sets the source of the ImageView:
ImageView ivPackageIcon = (ImageView)containingView.findViewById(R.id.ivPackageIcon);
if(ivPackageIcon != null) {
Bitmap coverImage = getBitmapFromAssets(containingView.getContext(), "myimage.png");
ivPackageIcon.setImageBitmap(coverImage);
}
The PNG image has some transparent areas, but for some reason when the image is displayed in my GridView, the transparent areas come through as black.
To preempt some questions: No, the background of the Activity, ImageView, GridView, and GridView item are not black. As a matter of fact, no matter what the background colors are set to, the transparent parts of the image always come through as black.
Consider this, though...If I place the PNG image in the drawable folder and set the ImageView as follows, the transparency is perfect:
ivPackageIcon.setImageResource(R.drawable.myimage);
I'm pretty sure that I'm using the decodeStream(...) method incorrectly somehow, but I don't know what I'm doing wrong. I even modified my original method to set some options as shown here:
public static Bitmap getBitmapFromAssets(Context context, String fileName) {
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
return bitmap;
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
But that gave me the same poor result.
Any ideas, anyone?
Thank you.
Instead this, try:
ImageView img=new ImageView(this);
Drawable d = Drawable.createFromStream(getAssets().open(path_in_assets), null);
img.setImageDrawable(d);
In case your image is made out of application resource and it is placed under res/drawable/ instead of one of the specific resolution folders (e.g. res/drawable-hdpi)
The android compiler is optimizing the PNG so the transparent pixels are made white (or black in case of GIFF files)
Resolution:
move your PNG file to res/drawable-hdpi or one of the other drawable folders, and you should be OK.
Related
I have problem when I try to set an image to a ImageView browsed from assets folder. When I place the same image in the drawable folder and use imageView.setImageResource(R.id.image); it is larger and fits the screen better than the image browsed by the previous method. Is there a way to resize the image so that it fits the screen exactly the same way as usual.
Here is the layout file and the code in java.
AssetManager manager = getActivity().getAssets();
InputStream input = null;
try {
input = manager.open("images/" + mQuestion.getQImage() + ".png");
} catch (IOException e) {
e.printStackTrace();
}
Bitmap image = BitmapFactory.decodeStream(input);
ImageView qImageView = (ImageView) questionView.findViewById(R.id.ImageView_qImage);
qImageView.setImageBitmap(image);
<ImageView
android:id="#+id/ImageView_qImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="#dimen/questionTopBottomMargin"
android:background="#color/radioButtonStrokeColor"
android:contentDescription="#string/hello_world"
android:padding="1px"
android:scaleType="fitXY" />
When you place an image in drawable folder then the images are classified on density of screen while if you put images in assest folder then android need to calculate density.
If you want to use images from assest folder then this code will help you.
Options opts = new BitmapFactory.Options();
opts.inDensity = DisplayMetrics.DENSITY_HIGH;
drawable = Drawable.createFromResourceStream(context.getResources(), null, is, srcName, opts);
see here
Image loaded from assets folder comes in different size than res/drawable
Android: Accessing images from assets/drawable folders
If you place images in the drawables folder they will be scaled by some functions it they load them from resources. This will not happen with images in assets folder which you load yourself.
Have a look at android docs
You should always use images from the drawable folder
There are different drawable folders in android
(drawable-hdpi,drawable-mdpi,drawable-ldpi)
Android will decide which folder image should be drawn depending on
the phone requirements and resolution
Use 9-patch image for auto-scaling
When you load from assets, the "source" density is unknown, so this
autoscaling is not performed. Hence, there is difference.
You just define the imageView width and height in the xml layout then you should try this code it works perfectly for me
public Bitmap getImageBitmap(String imgName){
AssetManager mgr = getAssets();
InputStream inputStream = null;
try {
inputStream = mgr.open(imgName + ".png");
return BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = getImageBitmap(imageName);
imageView.setImageBitmap(bitmap);
Alright i've spent several hours try to figure this out and most solutions didn't work, the one that did work made the height and width ratio of the image stay the same, what i want is to be able to set the imageview image from a URL and make the width match_parent and the height 175dp. PLEASE SOMEONE HELP ME!!!
use following code
<ImageView android:layout_width="match_parent"
android:layout_height="175dp"
android:scaleType="fitXY"
/>
public static void LoadImageFromWebOperations(String url,ImageView img) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
img.setImageDrawable(d);
} catch (Exception e) {
}
}
I have a byte array which contains an image fetched from the net. I am lazily loading them on my UI activity (or i am trying to at least :D ) using Bitmapfactory, BitmapDrawable and setImageDrawable. here is my code:
RelativeLayout r =(RelativeLayout) adap.getGroupView(Integer.parseInt(groupPos), false, null, null);
ImageView iv = (ImageView) r.findViewById(R.id.imgGruppo);
Log.w("",""+raw_img.length);
Bitmap bm = BitmapFactory.decodeByteArray(raw_img, 0, raw_img.length);
Drawable drawable = new BitmapDrawable(bm);
Log.i("","pre setimage");
iv.setImageDrawable(drawable);
//added for testing only, with no effects.
//((ELA) Activity_Titoli_2.this.getExpandableListAdapter()).notifyDataSetChanged();
//ELA is my expandable list adapter
Log.i("","post setimage"+bm.getRowBytes()); //just to see that i have actual data in raw_img and such
here is the XML involved
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayoutTitoli2_gruppo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textNomeGruppo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textColor="#FF0000"
android:padding="14dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textNoteGruppo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textNomeGruppo"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingBottom="7dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageView
android:id="#+id/imgGruppo"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:src="#drawable/icon"
/>
</RelativeLayout>
I have added "android:src..." just to check if the imageview is visible, and it is. The only problem is that i cannot change it!
I have tried setImageBitmap, using only the bitmap i created, i tried setimageDrawable creating a BitmapDrawable, but no effects at all. no errors, no nothing.
Please, where is the mistake? thank you
It's an out of memory problem, you can fix it using this method as below,
The "inSampleSize" option will return a smaller image and save memory. You can just call this in the ImageView.setImageBitmap
private Bitmap loadImage(String imgPath) {
BitmapFactory.Options options;
try {
options = new BitmapFactory.Options();
options.inSampleSize = 4;// 1/4 of origin image size from width and height
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
My guess is you're not doing this in the right thread. You could test this out by calling this code, then rotating the screen (or opening the physical keyboard, if you have one of those phones). This will cause the UI to refresh.
Anyway, what context are you calling this in? Background thread? You'd want to update the UI in the UI thread, or you'll have to call something like 'invalidate' on the View to get it to force a re-draw.
The below solution worked for me. I used Picasa library.
private Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(activity.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void bitmapIntoImageView(ImageView imageView, Bitmap bitmap, Activity activity){
Uri imageUri = getImageUri(bitmap);
Picasso.with(activity).load(imageUri).into(imageView);
}
public void imagePathIntoImageView(ImageView imageView, String imagePath, Activity activity) {
Uri imageUri = Uri.fromFile(new File(imagePath));
Picasso.with(activity).load(imageUri).into(imageView);
}
Picasa: http://square.github.io/picasso/
Call the below function to set the bitmap into ImageView
bitmapIntoImageView(imageView, bitmap, MainActivity.this)
I am looking for the way to assign image src to image view control. I read few example and they says something src="#drawable\image" but didn't understand this, also I want to assign image src at runtime by java code also want to apply default image in XML.
If you want to display an image file on the phone, you can do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));
If you want to display an image from your drawable resources, do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);
You'll find the drawable folder(s) in the project res folder. You can put your image files there.
You can set imageview in XML file like this :
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/imagep1" />
and you can define image view in android java file like :
ImageView imageView = (ImageView) findViewById(R.id.imageViewId);
and set Image with drawable like :
imageView.setImageResource(R.drawable.imageFileId);
and set image with your memory folder like :
File file = new File(SupportedClass.getString("pbg"));
if (file.exists()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap selectDrawable = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(selectDrawable);
}
else
{
Toast.makeText(getApplicationContext(), "File not Exist", Toast.LENGTH_SHORT).show();
}
In res folder select the XML file in which you want to view your images,
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/imagep1" />
shoud be #drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.
Drag image from your hard drive to Drawable folder in your project and in code use it like this:
ImageView image;
image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);
Is there a way to generate a drawable object from a layout?
In fact, I need a cropped part of my initial layout, and my idea is to transform the layout into a drawable object and then to crop drawable.
A simple version:
Bitmap snapshot = null;
Drawable drawable = null;
yourView.setDrawingCacheEnabled(true);
yourView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW); //Quality of the snpashot
try {
snapshot = Bitmap.createBitmap(yourView.getDrawingCache(), sizes and stuff); // You can tell how to crop the snapshot and whatever in this method
drawable = new BitmapDrawable(snapshot)
} finally {
yourView.setDrawingCacheEnabled(false);
}