Set imageview image from a url - android

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) {
}
}

Related

Unable to set LinearLayout BackgroundResource from URL using Picasso

I have a linearLayout I'd like to change the background of programatically:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/downloadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
...
and I've attempted to set the background Image of the XML layout using the following:
LinearLayout linearLayout2 = (LinearLayout) findViewById(R.id.downloadLayout);
int resId = getResources().getIdentifier(background,
"drawable", getPackageName());
linearLayout2.setBackgroundResource(resId);
However the background image never loads, there is no NPE, the image simply never loads. Any suggestions are appreciated.
I've done a bit of debugging and I currently have the following values:
linearLayout2 = android.widget.LinearLayout{529b3f58 V.E..... ......I. 0,0-0,0 #7f0a008e app:id/downloadLayout}
background = http://xxx.xxx.x.xxx/bgs/big_lebowski_bg.jpg
resID = 0
P.S.
I've also tried accomplishing the same using Picasso - I'm not sure how to get around the error stated and load it successfully:
Source:
final LinearLayout downloadLayout = (LinearLayout) findViewById(R.id.downloadLayout);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(downloadLayout);
Error:
The method into(Target) in the type RequestCreator is not applicable for the arguments (LinearLayout)
Picasso works with ImageViews only, not layouts.
You could put an ImageView inside your layout, set it to match parent's width and height, and inject the image into the ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/downloadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This should work then:
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);
You have to do so in the background thread and not on the main thread . Consider using image loading libraries such as Picasso
Example is
UPDATED
Make sure you have an image view in the LinearLayout and let it fill_parent (i.e the LinearLayout), Picasso is not applicable to an ImageView directly hence the error.
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
ALTERNATIVELY
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.yourLinearLayoutid);
BitmapDrawable drawableBitmap=new BitmapDrawable(getBitmap(urlString));
linearLayout.setBackgroundDrawable(drawableBitmap);
This method getBitMap, like the one in the Piccasso library should be sufficient without needing the library .
private Bitmap getBitmap(String url)
{
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

Android: Image from assets folder is smaller than it should be

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

How to display the image with aspected ratio?

In my application I want to display the image with aspected ratio like the gallery.In my application I have to display the marker image on image.Because the marker image having dragging functionality.So that the following is the xml for that
<RelativeLayout
android:background="#000000"
android:layout_above="#+id/buttonlayout"
android:id="#+id/imagelayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_centerInParent="true"
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
</RelativeLayout>
And in my activity after select the image from gallery, In onactivityresult method the following code I am using.
try {
// bmGallayImage = decodeFile(selectedImagePath);
bmGallayImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
bmRotated = InventorySubmitImagesActivity.rotateBitmap(bmGallayImage, orientation);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bmRotated!=null){
Drawable dr = new BitmapDrawable(bmRotated);
old_width=bmRotated.getWidth();
old_height=bmRotated.getHeight();
Log.e("gal bitmap height and width",""+old_height+" "+old_width);
relImage.getLayoutParams().height = old_height;
relImage.getLayoutParams().width = old_width;
relImage.setBackgroundDrawable(dr);
}
relImage.removeAllViews();
imgMarker = new ImageView(this);
final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
layoutParams.leftMargin = 0;
layoutParams.topMargin = 0;
relImage.addView(imgMarker, layoutParams);
imgMarker.setScaleType(ImageView.ScaleType.MATRIX);
bmdragImage=BitmapFactory.decodeResource(getResources(), R.drawable.image_marker);
imgMarker.setImageBitmap(bmdragImage);
In this code relImage is the referance of relative layout and imgMarker is the referance of image view. And the gallery image is set to the relative layout.And My device resolution is 480 by 800 and image resolution is 1920 by 1080.So this is the out put i am getting.
And gallery image view is like the bellow screen shot.
But my requirement is like the gallery image, i want to display the image with aspected ratio.So please suggest me how to do this. Thanks In Advance to all..
You can do this with FrameLayout put image view in this and put your marker ImageView like this http://chiuki.github.io/images/android-layout-101/frame-layout-center.png

Android: PNG Transparency Failing with BitmapFactory.decodeStream(...) and Assets Folder

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.

setImageBitmap has no visible effect

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)

Categories

Resources