Display full screen image in ImageView - android

I want to display full screen image on another activity after clicking an imageview. I have 6 ImageViews in my layout and each ImageView is getting image from Parse backend. How can I display image on fetching the imagepath ?
public ImageLoader imgl;
ImageView ad1,ad2,ad3,ad4,ad5,ad6;
List<ParseObject> ob;
private ImageView[] imgs = new ImageView[5];
int k=0;
ad1=(ImageView) findViewById(R.id.ad1);
ad2=(ImageView) findViewById(R.id.ad2);
ad3=(ImageView) findViewById(R.id.ad3);
ad4=(ImageView) findViewById(R.id.ad4);
ad5=(ImageView) findViewById(R.id.ad5);
ad6=(ImageView) findViewById(R.id.ad6);
imgs[0] = ad2;
imgs[1] = ad3;
imgs[2] = ad4;
imgs[3] = ad5;
imgs[4] = ad6;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Adverts");
query.orderByDescending("updatedAt");
query.whereEqualTo("Status", true);
try {
ob = query.find();
System.out.println("the urls areeee "+ob);
for (ParseObject country : ob) {
ParseFile image = (ParseFile) country.get("imageFile");
imgl.DisplayImage(image.getUrl(), imgs[k]);
k=k+1;
System.out.println("the urls are"+image.getUrl());
pd.dismiss();
}
} catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
pd.dismiss();
e.printStackTrace();
}
ad1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent ent= new Intent(HomeActivity.this,AdvertsActivity.class);
startActivity(ent);
}
});
}

Set click listener on your ImageView and pass your image url in argument and call method
private void viewImage(String url)
{
final Dialog nagDialog = new Dialog(ProjectDetailActivity.this,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
nagDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
nagDialog.setCancelable(false);
nagDialog.setContentView(R.layout.dialog_full_image);
ivPreview = (ImageView)nagDialog.findViewById(R.id.imageView1);
BitmapDrawable bmd = (BitmapDrawable)getDrawableFromUrl(url)
Bitmap bitmap = bmd.getBitmap();
ivPreview.setImageBitmap(bitmap);
nagDialog.show();
}
public Drawable getDrawableFromUrl(String imgUrl)
{
if(imgUrl == null || imgUrl.equals(""))
return null;
try
{
URL url = new URL(imgUrl);
InputStream in = url.openStream();
Drawable d = Drawable.createFromStream(in, imgUrl);
return d;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
use xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white"
android:layout_gravity="center" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="#string/hello_world"
android:src="#android:color/white"
android:layout_margin="5dp"
android:scaleType="centerInside"/>
</RelativeLayout>

Related

Show image from HTML tag in text view?

Xml Layout
<org.sufficientlysecure.htmltextview.HtmlTextView
android:id="#+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:lineSpacingExtra="5dp"
android:padding="5dp"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
Java
txtDescription.setHtml(object.getString("content"), new HtmlHttpImageGetter(txtDescription));
Response from server
{"success":"true","Content":{"id":115,"title":"vvipprogram","content":"<img src=\"https://example.com//media//images//topvvip.jpg" alt=\"topvvip\" width=\"43%\"\/>\r\n"}}
Result Screenshot
I Want to show this image in full page ? How to do this ? plz help me .
You can use this code for set html image and text both from textview:
This is xml code:
<TextView
android:id="#+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:lineSpacingExtra="5dp"
android:padding="5dp"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
This is Java code:
public class ConditionOfUseActivity extends Activity implements Html.ImageGetter {
private TextView txtDescription;
private Drawable empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_condition_use);
txtDescription = (TextView) findViewById(R.id.txtDescription);
String source = "this is a test of <b>ImageGetter</b> it contains " +
"two images: <br/>" +
"<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" +
"<img src=\"http://developer.android.com/assets/images/icon_search.png\">";
Spanned spanned = Html.fromHtml(object.getString("content"), ConditionOfUseActivity.this, null);
txtDescription.setText(spanned);
}
#Override
public Drawable getDrawable(String s) {
LevelListDrawable d = new LevelListDrawable();
empty = getResources().getDrawable(R.drawable.splash1);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(s, d);
return d;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
private LevelListDrawable mDrawable;
#Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(bitmap);
mDrawable.addLevel(1, 1, d);
//mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
mDrawable.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
mDrawable.setLevel(1);
CharSequence t = txtDescription.getText();
txtDescription.setText(t);
}
}
}

Exception in ImageLoader fetching images from Parse.com

I'm trying to fetch images from Parse.com in the array of ImageViews. However, the app is crashing with nullpointerException in ImageLoader class. I have 5 images in parse.com and 6 ImageViews. one ImageView has an image set in drawable folder. So 5 images get loaded dynamically from parse in array of Imageviews 1-6. HomeActivity is :
ImageView ad1,ad2,ad3,ad4,ad5,ad6;
List<ParseObject> ob;
private ImageView[] imgs = new ImageView[5];
int k=0;
public ImageLoader imgl;
in onCreate():
imgl=new ImageLoader(getApplicationContext());
ad1=(ImageView) findViewById(R.id.ad1);
ad2=(ImageView) findViewById(R.id.ad2);
ad3=(ImageView) findViewById(R.id.ad3);
ad4=(ImageView) findViewById(R.id.ad4);
ad5=(ImageView) findViewById(R.id.ad5);
ad6=(ImageView) findViewById(R.id.ad6);
imgs[0] = ad2;
imgs[1] = ad3;
imgs[2] = ad4;
imgs[3] = ad5;
imgs[4] = ad6;
try {
// Locate the class table named "Footer" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Adverts");
query.orderByDescending("updatedAt");
query.whereEqualTo("Status", true);
ob = query.find();
for (ParseObject country : ob) {
ParseFile image = (ParseFile) country.get("imageFile");
imgl.DisplayImage(image.getUrl(), imgs[k]);
k=k+1;
System.out.println("the urls are"+image.getUrl());
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In ImageLoader class:
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.ic_launcher;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
I'm getting nullpointer at imageView.setImageResource(stub_id);
Please help.
only reason a null pointer can appear for a placeholder is ur imageview is null...May be
you have to double check whether view is passed properly

Textview below each image in a galleryview

In my application i am using some 5 galleryview to display the image, done correctly,i can able to populate the image correctly.Now i want to add textview below each image.
I want gallery view like this:
image1 Image2 Image3 image4
-------->Galleryview1
text1 text2 text3 text4
------------------------------------------
image1 image2 image3 image4
--------->Galleryview2
text1 text2 text3 text4
My code:
Adapter code:
public class GalleryviewAdapter extends BaseAdapter
{
static final String URL="http://aaaa/home.xml";
public static GalleryviewAdapter instance=new GalleryviewAdapter();
public static GalleryviewAdapter getInstance()
{
return instance;
}
Context context;
GalleryviewAdapter()
{
System.out.println("Inside cons");
getelement();
// getelementindia();
}
// String[] itemsArray =
// {
// "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"
// };
// MyAdapter(Context c)
// {
// context = c;
// }
private Activity activity;
private LayoutInflater inflater=null;
public void ImageAdapter(Activity a)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
String imageurl[]= {};//new String[5];
// String imageurlindia[]={};
public void getelement()
{
System.out.println("Inside getelement");
// String[] itemsarray={};
// ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
// ArrayList<String> menuItems = new ArrayList<String>();
TaplistingParser parser = new TaplistingParser();
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
// System.out.println("sssss="+doc);
NodeList nl=doc.getElementsByTagName("article");
imageurl = new String[nl.getLength()];
System.out.println("len="+nl.getLength());
for(int i=0; i < nl.getLength(); i++ )
{
// System.out.println("Inside for");
// HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// map.put("SectionName", parser.getValue(e, "sectionname"));
// System.out.println("b4 items="+parser.getValue(e, "sectionname"));
// itemsarray[i] = parser.getValue(e, "sectionname");
// System.out.println("items="+itemsarray[i]);
imageurl[i]=parser.getValue(e, "kickerimage");
// menuItems.add(parser.getValue(e, "sectionname"));
// menuItems.add(parser.getValue(e, "sectionname"));
// System.out.println("menu="+menuItems);
}
// String[] itemsarray = menuItems.toArray(new String[menuItems.size()]);
// String[] itemsarray = new String[menuItems.size()];
// itemsarray=menuItems.toArray(itemsarray);
//// for(int j= 0;j < itemsarray.length;j++ )
//// {
//// Log.d("string is",(itemsarray[j]));
//// }
// return itemsarray;
}
public int getCount()
{
// TODO Auto-generated method stub
return imageurl.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return imageurl[position];
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// System.out.println("sssssssss="+imageurl[position]);
// View vi=convertView;
// ViewHolder holder;
// if(convertView==null)
// {
// vi = inflater.inflate(R.layout.main, null);
// holder=new ViewHolder();
// holder.text=(TextView)vi.findViewById(R.id.Txt01);
// holder.image=(ImageView)vi.findViewById(R.id.imageview1);
// vi.setTag(holder);
// }
Bitmap bitmap=DownloadImage(imageurl[position]);
View rowView = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.main, null);
//
ImageView imgview=(ImageView)rowView.findViewById(R.id.imageview1);
imgview.setImageBitmap(bitmap);
//
// ImageView imgviewindia=(ImageView)rowView.findViewById(R.id.imageviewindia);
// imgviewindia.setImageBitmap(bitmap);
// TextView listTextView = (TextView)rowView.findViewById(R.id.);
// listTextView.setText(getelement()[position]);
return rowView;
}
private Bitmap DownloadImage(String URL)
{
// System.out.println("image inside="+URL);
Bitmap bitmap = null;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("image last");
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
// }
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageview1"
android:layout_marginLeft="10dp"
android:layout_marginTop="-20dp"
android:layout_width="120dp"
android:layout_height="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/Txt01" />
</LinearLayout>
My main activitycode:
public class NewspapperActivity extends Activity
{
/** Called when the activity is first created. */
Context ctx;
static final String URLHeading = "http://aaaaaa.in/cccccc.xml";
String[] headingurl=new String[20];
// ListViewwithimageAdapter adapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.galleryview);
// ArrayList<String>item = new ArrayList<String>();
Heading parser = new Heading();
String xmldata = parser.getXmlFromUrl(URLHeading);
Document domelement = parser.getDomElement(xmldata);
NodeList node = domelement.getElementsByTagName("item");
// int i ;
TextView txt1 = (TextView)findViewById(R.id.Text01);
TextView txt2 = (TextView)findViewById(R.id.Text02);
TextView txt3 = (TextView)findViewById(R.id.Text03);
TextView txt4 = (TextView)findViewById(R.id.Text04);
TextView txt5 = (TextView)findViewById(R.id.Text05);
// glly.setAdapter(adapter);
// System.out.println("prakash4");
// for(i=0 ; i < node.getLength();i++)
// {
Element e0 = (Element) node.item(0);
txt1.setText(parser.getValue(e0, "sectionname"));
Element e1 = (Element) node.item(1);
txt2.setText(parser.getValue(e1, "sectionname"));
Element e2 = (Element) node.item(2);
txt3.setText(parser.getValue(e2, "sectionname"));
Element e3 = (Element) node.item(3);
txt4.setText(parser.getValue(e3, "sectionname"));
Element e4 = (Element) node.item(4);
txt5.setText(parser.getValue(e4, "sectionname"));
Gallery glly= (Gallery)findViewById(R.id.Gallery01);
Gallery glly2= (Gallery)findViewById(R.id.Gallery02);
Gallery glly3= (Gallery)findViewById(R.id.Gallery03);
Gallery glly4= (Gallery)findViewById(R.id.Gallery04);
Gallery glly5= (Gallery)findViewById(R.id.Gallery05);
// GridView gv = (GridView)findViewById(R.id.grid);
// ListViewwithimageAdapter adapter = ListViewwithimageAdapter.getInstance();
GalleryviewAdapter adapter=GalleryviewAdapter.getInstance();
glly.setAdapter(adapter);
glly.setSelection(1);
glly2.setAdapter(adapter);
glly2.setSelection(1);
glly3.setAdapter(adapter);
glly3.setSelection(1);
glly4.setAdapter(adapter);
glly4.setSelection(1);
glly5.setAdapter(adapter);
glly5.setSelection(1);
// item.add(parser.getValue(e, "sectionname"));
// }
// gv.setAdapter(new GridviewImageAdapter(this));
}
}
I am new to this ..Please help me.Thanks in advance..
Use below xml code instead of your xml code, it will solve your problem and if you have any problem regarding that then tell me.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageview1"
android:layout_width="120dp"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="-20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/ic_launcher"/>
<TextView
android:id="#+id/Txt01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageview1"
android:layout_centerHorizontal="true"
android:text="Dipak" />
</RelativeLayout>
</RelativeLayout>

Inserting image from assets folder into a ListView

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl("http://domain.com/directory/database/retrieveComments.php?placeId=" + stringPlaceId);
try
{
commentsRatingsArray = json.getJSONArray("commentsRatings");
for(int i = 0; i < commentsRatingsArray.length(); i++)
{
JSONObject jsonObject = commentsRatingsArray.getJSONObject(i);
String dbUserFullName = jsonObject.getString(TAG_FULLNAME);
String dbUserEmail = jsonObject.getString(TAG_EMAIL);
String dbComment = jsonObject.getString(TAG_COMMENT);
String dbRating = jsonObject.getString(TAG_RATING);
String dbDate = jsonObject.getString(TAG_DATE);
String dbTime = jsonObject.getString(TAG_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FULLNAME, dbUserFullName);
map.put(TAG_EMAIL, dbUserEmail);
map.put(TAG_COMMENT, dbComment);
map.put(TAG_RATING, dbRating);
map.put(TAG_DATE, dbDate);
map.put(TAG_TIME, dbTime);
list.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
}
ListAdapter adapter = new SimpleAdapter
(DisplayCommentsRatings.this, list, R.layout.commentrating,
new String[] { TAG_FULLNAME, TAG_EMAIL, TAG_COMMENT, TAG_DATE, TAG_TIME },
new int[] {R.id.tvUserFullName, R.id.tvUserEmail, R.id.tvUserComment, R.id.tvDate, R.id.tvTime });
setListAdapter(adapter);
Here's my code, I'm getting these JSON Array values from my database. I just want to know how to change an image's src inside a list view. Because I will only use 5 images, I decided to include these images in my assets folder instead of uploading them to the web.
Can someone give me an idea to make this possible?
Here's my XML code:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvUserFullName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12dip"
android:textStyle="bold"/>
//This is the imageView where I will display the image from the assets folder
<ImageView
android:id="#+id/ivUserRating"
android:layout_width="100dip"
android:layout_height="fill_parent"
android:src="#drawable/zerostar"/>
</LinearLayout>
<TextView
android:id="#+id/tvUserEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EmailAddress#domain.com"
android:textSize="9dip"/>
<TextView
android:id="#+id/tvUserComment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text='"This is a comment. This is a comment. This is a comment. This is a comment. This is a comment."'
android:textSize="10dip"
android:layout_margin="3dip"
android:textColor="#000000"
android:maxLength="300"/>
<TextView
android:id="#+id/tvDate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="August 1, 2010"
android:textColor="#000000"
android:textSize="8dip"
android:layout_gravity="right"/>
<TextView
android:id="#+id/tvTime"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="08:20 PM"
android:textColor="#000000"
android:textSize="8dip"
android:layout_gravity="right"/>
Use SimpleAdapter as normal, but be sure to override you "adapter"'s the setViewBinder method like:
adapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// Check wether it's ImageView and the data
if(view instanceof ImageView && data instanceof Bitmap){
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}else
return false;
}
});
then use a getBitmap() to get the assert image
public Bitmap getBitmap( String path, int i ){
Bitmap mBitmap = null;
try {
AssetManager assetManager = getAssets();
String[] files = null;
files = assetManager.list( "smartmodel/" + path );
Log.i( "Assert List", files[1].toString() );
// Pass ur file path, here is one in assert/smartmodel/ filer
mBitmap = BitmapFactory.decodeStream( this.getAssets().open( "smartmodel/" + path + "/"+ files[i]) );
} catch (Exception e) {
e.printStackTrace();
}
return mBitmap;
}
Last, in your Simple adapter List parameter, put
map.put( "ItemImage", getBitmap( gridItemName, i ));
Your passed getBitmap(...) will be show.
check position and use like,
Bitmap bmp=null;
if(position==0){
bitmap=getBitmap("img0.png");
}else if (position==1){
bitmap=getBitmap("img1.png");
}
.
.
.
Method::
private Bitmap getBitmap(String name) throws IOException
{
AssetManager asset = getAssets();
InputStream is = asset.open(name);
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}

Show Image View from file path?

I need to show an image by using the file name only, not from the resource id.
ImageView imgView = new ImageView(this);
imgView.setBackgroundResource(R.drawable.img1);
I have the image img1 in the drawable folder. I wish to show that image from the file.
How can I do this?
Labeeb is right about why you need to set image using path if your resources are already laying inside the resource folder ,
This kind of path is needed only when your images are stored in SD-Card .
And try the below code to set Bitmap images from a file stored inside a SD-Card .
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);
}
And include this permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I think you can use this
Bitmap bmImg = BitmapFactory.decodeFile("path of your img1");
imageView.setImageBitmap(bmImg);
You can also use:
File imgFile = new File(“filepath”);
if(imgFile.exists())
{
ImageView myImage = new ImageView(this);
myImage.setImageURI(Uri.fromFile(imgFile));
}
This does the bitmap decoding implicit for you.
All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.
Did I mention it is super easy to use:
Picasso.with(context).load(new File(...)).into(imageView);
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(myBitmap);
}
From the official site: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
ImageView image = (ImageView) findViewById(R.id.imagePreview);
try {
image.setImageBitmap(decodeSampledBitmap(picFilename));
} catch (Exception e) {
e.printStackTrace();
}
Here the methods:
private int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Bitmap decodeSampledBitmap(String pathName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
//I added this to have a good approximation of the screen size:
private Bitmap decodeSampledBitmap(String pathName) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
return decodeSampledBitmap(pathName, width, height);
}
How To Show Images From Folder path in Android
Very First: Make Sure You Have Add Permissions into Mainfest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
:Make a Class MyGallery
public class MyGallery extends Activity {
private GridView gridView;
private String _location;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
private AdView mAdView;
private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
public static String[] imageFileList;
TextView gallerytxt;
public static ImageAdapter imageAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mygallery);
/*if (MenuClass.mInterstitialAd.isLoaded()) {
MenuClass.mInterstitialAd.show();
}*/
gallerytxt = (TextView) findViewById(R.id.gallerytxt);
/*gallerytxt.setTextSize(20);
int[] color = {Color.YELLOW,Color.WHITE};
float[] position = {0, 1};
Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
Shader shader_gradient0 = lin_grad0;
gallerytxt.getPaint().setShader(shader_gradient0);*/
ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyGallery.this.finish();
}
});
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
gridView = (GridView) findViewById(R.id.gridView);
new MyGalleryAsy().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(MyGallery.this, ImageDetail.class);
intent.putExtra("ImgUrl", imageFileList[pos]);
//Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
if (ImageDetail.deleted) {
photo = new ArrayList<Bitmap>();
new MyGalleryAsy().execute();
ImageDetail.deleted = false;
}
}
public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
Bitmap mBitmap;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
readImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
DisplayMetrics displayMatrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
int screenWidth = displayMatrics.widthPixels / 3;
if (photo.size() > 0) {
imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
gridView.setAdapter(imageAdapter);
}
}
}
private void readImage() {
// TODO Auto-generated method stub
try {
if (isSdPresent()) {
_location = extStorageDirectory + newFolder;
} else
_location = getFilesDir() + newFolder;
File file1 = new File(_location);
if (file1.isDirectory()) { // sdCard == true
imageFileList = file1.list();
if (imageFileList != null) {
for (int i = 0; i < imageFileList.length; i++) {
try {
photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private int width;
private int mGalleryItemBackground;
public ImageAdapter(Context c) {
context = c;
}
public ImageAdapter(Context c, int width) {
context = c;
this.width = width;
}
public int getCount() {
return photo.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.galleryadapter, null);
RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);
ImageView imageView = new ImageView(context);
layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setImageBitmap(photo.get(position));
return v;
}
public void updateItemList(ArrayList<Bitmap> newItemList) {
photo = newItemList;
notifyDataSetChanged();
}
}
}
Now create its Xml Class
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="#+id/gallerytxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:fontFamily="#string/font_fontFamily_medium"
android:text="My Gallery"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black"
android:textStyle="bold" />
<ImageButton
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center|bottom"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id" />
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/adView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/relativeLayout"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:smoothScrollbar="true"
android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]
To see the Image in Detail create a new Class ImageDetail:##
public class ImageDetail extends Activity implements OnClickListener {
public static InterstitialAd mInterstitialAd;
private ImageView mainImageView;
private LinearLayout menuTop;
private TableLayout menuBottom;
private Boolean onOff = true;
private ImageView delButton, mailButton, shareButton;
private String imgUrl = null;
private AdView mAdView;
TextView titletxt;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
public static boolean deleted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.image_detail);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mainImageView = (ImageView) findViewById(R.id.mainImageView);
menuTop = (LinearLayout) findViewById(R.id.menuTop);
menuBottom = (TableLayout) findViewById(R.id.menuBottom);
titletxt = (TextView) findViewById(R.id.titletxt);
titletxt.setTextSize(22);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
delButton = (ImageView) findViewById(R.id.delButton);
mailButton = (ImageView) findViewById(R.id.mailButton);
shareButton = (ImageView) findViewById(R.id.shareButton);
Bundle exBundle = getIntent().getExtras();
if (exBundle != null) {
imgUrl = exBundle.getString("ImgUrl");
}
if (isSdPresent()) {
imgUrl = extStorageDirectory + newFolder + imgUrl;
} else
imgUrl = getFilesDir() + newFolder + imgUrl;
if (imgUrl != null) {
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
Glide.with(this).load(imgUrl).into(imageViewTarget);
}
delButton.setOnClickListener(this);
mailButton.setOnClickListener(this);
shareButton.setOnClickListener(this);
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.shareButton:
Image_Link();
break;
case R.id.delButton:
deleted();
break;
case R.id.mailButton:
sendemail();
break;
default:
break;
}
}
private void sendemail() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Image_Link() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void deleted() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
builder.setTitle(getString(R.string.removeoption));
builder.setMessage(getString(R.string.deleteimage));
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
File fileDel = new File(imgUrl);
boolean isCheck1 = fileDel.delete();
if (isCheck1) {
deleted = true;
finish();
MyGallery.imageAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
}
Create its xml image_detail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<ImageView
android:id="#+id/mainImageView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:contentDescription="#string/app_name"
android:focusable="true"
android:focusableInTouchMode="true" />
<LinearLayout
android:id="#+id/adlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:visibility="gone"></LinearLayout>
<LinearLayout
android:id="#+id/menuTop"
android:layout_width="fill_parent"
android:layout_height="56dp"
android:layout_alignWithParentIfMissing="true"
android:layout_below="#+id/adlayout"
android:background="#color/colorPrimary"
android:orientation="vertical"
android:padding="10.0dip"
android:visibility="visible">
<TextView
android:id="#+id/titletxt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Islamic Gifs"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
<TableLayout
android:id="#+id/menuBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:padding="10.0dip"
android:stretchColumns="*"
android:visibility="visible">
<TableRow>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/mailButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/shareButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage_small"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/delButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_delete"
android:contentDescription="#string/app_name" />
</LinearLayout>
</TableRow>
</TableLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/menuTop"
android:layout_centerHorizontal="true"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id"></com.google.android.gms.ads.AdView>
Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="#drawable/result_bt_mail_s"/>
Dont forget to add in application tag for sdk version 29 and 30 to add this line
android:requestLegacyExternalStorage="true"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
onLoadImage Full load
private void onLoadImage(final String imagePath) {
ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size
//ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(final String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
progress2.setVisibility(View.VISIBLE);
new Handler().post(new Runnable() {
public void run() {
progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
// Picasso.with(getContext()).load(imagePath).into(imageView);
// Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);
Glide.with(getContext())
.load(imagePath)
.asBitmap()
.into(imageView);
}
});
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
// else {
Log.e("onLoadImage", "onLoadingComplete");
// progress2.setVisibility(View.INVISIBLE);
// }
// setLoagingCompileImage();
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadingFailed", imageUri);
Log.e("onLoadingFailed", failReason.toString());
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
super.onLoadingCancelled(imageUri, view);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadImage", "onLoadingCancelled");
}
});
}
private void showImage(ImageView img, String absolutePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
img.setImageBitmap(bitmapPicture);
}
Most of the answers are working but no one mentioned that the high resolution image will slow down the app , In my case i used images RecyclerView which was taking 0.9 GB of device memory In Just 30 Images.
I/Choreographer: Skipped 73 frames! The application may be doing too
much work on its main thread.
The solution is Sipmle you can degrade the quality like here : Reduce resolution of Bitmap
But I use Simple way , Glide handles the rest of work
fanContext?.let {
Glide.with(it)
.load(Uri.fromFile(File(item.filePath)))
.into(viewHolder.imagePreview)
}
You can easily do this using bitmap. You can find the code below :
ImageView imageView=findViewById(R.id.imageView);
Bitmap bitMapImage= BitmapFactory.decodeFile("write path of your image");
imageView.setImageBitmap(bitMapImage);
mageView.setImageResource(R.id.img);

Categories

Resources