i try to load image fro url and show imageview.i wrote code witch can download image and show it.but now i want to download facebook user image and show it.i know how i can check facebook user image "like this
http://graph.facebook.com/user id /picture?width=80&height=80
when i run programm i have RuntimeException
this is a my source
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
user_img.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
new GetXMLTask().execute((new String[] { URL }));
if my url would be for example http://mywebsite./pic.jpg then program working perfect but i want show facebook user image
You should be using picasso.
Add dependency into your project. And further just a singe line of code will do the task.
Picasso.with(context).load("http://somepath/someimage.png").into(imageView);
No need of writing thread and optimizing bitmaps.
You can refer : http://square.github.io/picasso/
Related
So the title slightly misleading. I've put the URl in a drawable.
public Drawable getDrawableFromURL(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
I had it has a bitmap originally but kept getting nullpointers and android.os.NetworkOnMainThreadException, which I've managed to fix, but the nullpointer comes around again. So I'm stuck on how to save to internal, because I can save it to SD fine.
Thanks
try this
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
// save your bitmap here
}
}
to call this AsyncTask use below code
new DownloadImage().execute(url);
I am new for android. I Want to get image from url and set into Bitmap variable.I tried so many code but i didn't get.
Here my code:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
ImageDownloaderTask.java
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
bImage = result;
}
}
Thanks in advance...
Here is code you can use
new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Do whatever you want to do with the bitmap
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
From your code,
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
you get an empty image because your ImageDownloaderTask not yet finished downloadin the image.
Try updating image on your onPosExecute:
protected void onPostExecute(Bitmap result) {
bImage = result;
// Update image here.
}
Bitmap bmp;
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmp=result
}}
try this,
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
In my opinion its best to create an interface for this:
public interface ImageDownloaderResponse {
void downloadFinished(Bitmap bm);
}
In your ImageDownloaderTask:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
public ImageDownloaderResponse delegate = null;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
delegate.downloadFinished(result);
}
}
Then let your activity/fragment implement the interface like this:
public class MainActivity extends AppCompatActivity implements ImageDownloaderResponse {
And use your Downloadtask like this:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(url);
And add this to your activity/fragment:
#Override
public void downloadFinished(Bitmap bm) {
Bitmap bitmap = bm;
}
Try below code:
URL url = new URL("https://www.google.com/intl/en_ALL/images/logo.gif");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
And add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
I trying read a external imagen but I've the error
"android.os.NetworkOnMainThreadException" and
"http.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)"
OnCreate
imageView = (ImageView) findViewById(R.id.image_view);
downloadFile(imageHttpAddress);
Function downloadFile
void downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
imageView.setImageBitmap(loadedImage);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
From Android docs
You should not perform network operations on the UI thread.
To avoid this exception, you can use AsyncTask for your request.
imageView = (ImageView) findViewById(R.id.image_view);
new AsyncTask<String, Void, Bitmap>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... url) {
return downloadFile(url[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(imageHttpAddress);
private Bitmap downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
return loadedImage;
} catch (IOException e) {
e.printStackTrace();
}
}
Even better, use some Async image handling library for android. there are many of these around the internet. A very popular one is picasso
You can use this function ;)
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
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");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap
}
I have some images in my Servlet that I want to download into my Android app.
I am performing a GET request to this URL:
public static final String URL ="http://myIpAddress:8080/imgs";
And this class doing the job:
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
StaggeredPrenotaTour staggeredPrenotaView;
public GetXMLTask(StaggeredPrenotaTour listView){
this.staggeredPrenotaView = listView;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
staggeredPrenotaView.pullTours(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
and in my Servlet:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
BufferedImage bi = ImageIO.read(st); **//error here**
OutputStream out = resp.getOutputStream();
//Todo send InputStream into OutputStream
ImageIO.write(bi, "jpg", out);
out.close();
}
I would like to receive an InputStream containing my Bitmap image but I receive the following error:
WARNING: Error for /imgs
java.lang.NoClassDefFoundError: javax.imageio.ImageIO is a restricted class.Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at madapps.bicitourbo.backend.MyServlet.doGet(MyServlet.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
...
Why do you need to use ImageIO? You can do simply something like:
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
OutputStream os = resp.getOutputStream();
if (st != null) {
byte[] buf = new byte[4096];
int nRead;
while( (nRead=st.read(buf)) != -1 ) {
os.write(buf, 0, nRead);
}
st.close();
}
I have this code to download a photo from a URL and display it in an ImageView on Android.
I am not sure how to loop this if I had a ArrayList or Array of multiple Urls to download and display on different ImageViews. I would appreciate any help or insight on how to proceed! Thank you!
public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
//sets bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView1 = (ImageView) findViewById(R.id.imageView);
imageView1.setImageBitmap(result);
}
//creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
//makes httpurlconnection and returns inputstream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
You can for example make a result of AsyncTask as List ant write something like this
protected Bitmap doInBackground(String... urls) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>;
for (String url : urls) {
bitmaps.add(downloadImage(url));
}
return bitmaps;
}
protected void onPostExecute(List<Bitmap> result) {
//...
}
But what I really would recommend you is to use Volley library written by Google, it has really easy and powerful API (here is Google I/O session about it https://developers.google.com/live/shows/474338138 and repository https://android.googlesource.com/platform/frameworks/volley/)