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

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

Related

is it possible to load images from the directory on web server?

I am currently using nostra image loader for loading images...
in my code i am using like this..
public static final String[] IMAGES = {"http://mywebsite.com/tittle/image1.jpg",
"http://mywebsite.com/tittle/image2.jpg",
"http://mywebsite.com/tiitle/image3.jpg",
"http://mywebsite.com/tittle/image4.jpg",
"http://mywebsite.com/tittle/image5.jpg",....};
Is it possible load images from the directory which has images in it..
like ""http://mywebsite.com/tittle"
You want to download all images from a single directory right ?
File directory= new File("some public directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("jpg"))
{
//get file here
}
}
Your question is not clear. Can you elaborate which directory are you taking about. Is it the SD Card directory (external memory) , Phone directory (internal memory) or a directory on the web server.
Still for the answer, you can load images from all the above 3 mentoined memories.
This the process of downloading any image from the web server and saving it to local memory:
public class DownloadImage
{
public DownloadImage(String url,String file) throws IOException
{
File fileName = new File(file);
URL myImageURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection)myImageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
OutputStream fOut = null;
fOut = new FileOutputStream(fileName);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
}
Make a new class named DownloadImage and copy the above code. Then in "url" pass the HTTP Url from where the image has to be downloaded and in "file" pass the local memory address where the image has to be stored.

Android sharing image not working

I'm trying to share an image in an app I have made that downloads an Image and writes it to a file. But any time I try to share it, it says can't upload file or just does nothing. It's not coming up in the logcat so I'm kinda stuck for ideas on how to fix it.
The image that is downloaded is displayed in an image view like this
iView.setImageBitmap(im);
String path = ContentFromURL.Storage + "/temp.jpg";
File temp = new File(path);
uri = Uri.fromFile(temp);
iView.setImageURI(uri);
Asynch task to download file
HttpURLConnection connection;
try {
String url = params[0];
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset","UTF-8");
connection.connect();
InputStream input = connection.getInputStream();
image = BitmapFactory.decodeStream(input);
File temp = new File(Storage,"temp.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = new FileOutputStream(temp);
fo.write(bytes.toByteArray());
fo.close();
String path = temp.getAbsolutePath();
Log.d("Asynch", "image shuould exist");
SharePage.act.runOnUiThread(new Runnable()
{
public void run()
{
SharePage.setImage(image);
}
}
);
creating intent
twitterIntent = new Intent(Intent.ACTION_SEND);
twitterIntent.setClassName("com.twitter.android",packageName);
twitterIntent.setType("image/jpeg");
twitterIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(twitterIntent);
I know that I should use the built in android share thing but its not working either when I try to share the image
The problem was where I was trying to store the Image, I wanted to have it so that the user never saw the image and it was deleted when it wasn't needed anymore but the other apps didn't have access to the directory. So I have since moved it to the external storage directory.

How to set android imageview from downloaded png

I have a database online that gives image file locations and file names
I am trying to update an imageview in an android screen. Here is my code that gets the image and the things I have tried:
// successfully received product details
JSONArray productObj = json.getJSONArray("product"); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// imageview
imageVw = (ImageView) findViewById(R.id.imageView1);
// display data in imageview
//imageStr = "http://somesite.com/images/" + product.getString("imagefile");
imageStr = "file://somesite.com/images/" + product.getString("imagefile");
//imgUri=Uri.parse("file:///data/data/MYFOLDER/myimage.png");
//imgUri=Uri.parse(imageStr);
//imageVw.setImageURI(imgUri);
imageVw.setImageBitmap(BitmapFactory.decodeFile(imageStr));
You can do something like this if you want to get the Bitmap of the image stored on the web. I personally use the library called ImageDownloader. The library is simple to use.
You have to understand that "A URL is a URI but a URI is not a URL. A URL is a specialization of URI that defines the network location of a specific representation for a given resource." so, if your file location is http then you need to make the function like below to get the Bitmap. I use ImageDownloader library because it runs its own thread and also manages some caches for faster image downloads.
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}

How can I convert response json string image into a displayable image

My final year project requires me to develop a mobile application which fetches a number of Json values from a server. This is my first experience in android development but sure learned something’s and enjoyed the experience.
I have managed to develop the following.
1-a json parser class which fetches the value.
2-a class which displays these values.
3-a database where I store the json response.
However I'm one step away from completing my project, I cannot display the response string image address as real images (shame on me).
I need to do the following.
1- Parse the string path of the image and display the response as image.
I have spent most of my time trying to find the solution on the web, stack overflow. But no luck so far.
I need to do something like this in order to display these images together with the text descriptions.
I have now reached the cross roads and my knowledge has been tested.Is what i'm trying to do here posible?.
Who can show me the way? ,to this outstanding platform.
if you have the image url as a string, you can load and save the image using something like this:
try {
Bitmap bitmap = null;
File f = new File(filename);
InputStream inputStream = new URL(url).openStream();
OutputStream outputStream = new FileOutputStream(f);
int readlen;
byte[] buf = new byte[1024];
while ((readlen = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, readlen);
outputStream.close();
inputStream.close();
bitmap = BitmapFactory.decodeFile(filename);
return bitmap;
} catch (Exception e) {
return null;
}
For saving, make sure you have appropriate permissions if you're going to save to sdcard.
if you just want to load the image (without saving):
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
Just make sure you fetch the image in a separate thread or using AsyncTask or else you'll get ANRs!
you can try this ImageDownloader class from google. It´s works nice :)
Is an AsynkTask that handle the download and set the bitmap to an ImageView.
ImageDownloader
Usage:
private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);

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