I am working on API. We have provided Url of Images. I have to show image from that Url in my list Activity for which custom Adapter is used. How can I set image throw url? I have spent almost two days in it. I used image view in my Activity.
try below code in your activity, you will get Bitmap object, using setImageBitmap(Bitmap bmt) you can do.
Method:
public Bitmap getBitmap(String url) {
Log.d("getBitmap", "getBitmap");
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(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return bm;
}
inner class:
class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
}
see this complete example
Use this code to get bitmap image from file ,
Bitmap bitmapImage = BitmapFactory.decodeFile(//File path);
imageView.setImageBitmap(bitmapImage);
and you can get file from uri through the below method ,
private File getFileFromUri(Uri uri) throws IOException {
Cursor cursor = managedQuery(uri, null, null, null, null);
if (cursor.getCount() == 0) {
throw new IOException(String.format("cannot find data from %s",
uri.toString()));
} else {
cursor.moveToFirst();
}
String filePath = cursor.getString(cursor
.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
}
Hope this will be helpful to you
Related
My code: holder.icon.setImageResource(current.imageUrl); here the imageUrl is been declared in String. But setImageResource takes only int. Can anyone provide me a solution how to get a string or is there anyother method available for it?
I think u are fetch the image from internet.
private Bitmap getBitMapFromUrl( String imageuri){
HttpURLConnection connection=null;
try {
URL url=new URL(imageuri);
connection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap mybitmap=BitmapFactory.decodeStream(is);
return mybitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}}
pass the string value and return the bitmap.
holder.icon.setImageBitmap(getBitmapFromUrl());
you are using the "setImageResource" !
it expects a Resource (usually a drawable resource), hence the int requirement.
the download solution suggested by #Mayuri Joshi might fit your needs, if not, please provide more information regarding what it is you are trying to accomplish :)
You have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView
I have the code for downloading image from URL to SDCard, but my device can set up the image ONLY from bitmap.
The question is how I can consume image from URL directly into SQLite Database and then retreive it as the bitmap?
Thanks for any help
public void getNewLogoFromURL(String logo) throws IOException {
new GetLogo().execute(logo);
}
class GetLogoForReceipt extends AsyncTask <String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
downloadFile(params[0]);
} catch ( IOException e ) {
}
return null;
}
}
public void downloadFile(String url) throws IOException {
DataOutputStream fos = null;
try {
File dest_file = new File("/sdcard/Pictures/applicationLogo.png");
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
} finally {
fos.close();
}
}
//Device image settingUp code
String[] fileList = { "applicationLogo.png" };
Bitmap[] bitmap = new Bitmap[fileList.length];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/Pictures/applicationLogo.png", options);
for ( int i = 0; i < fileList.length; i++ ) {
bitmap[i] = bitmap2;
}
int ret;
printer = new LinePrinter();
ret = printer.open(device);
ret = printer.setBitmap(bitmap);
Storing bitmaps/images in sqlite database is a bad idea. Download the image to the sd card and save the location in the data base and retrieve the image from sd card when you required.
The below code shows getting bitmap from sdcard.
public Bitmap createBitMap(String path){
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return bitmap;
}
I want to convert bitmap to URI conversion I am using google image search API from this API I got image URL from this URL I converted it to a bitmap then I want to convert from this bitmap to URI using this sample but I get a null value.
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) {
imagQest.setImageBitmap(result);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(ctx.getContentResolver(),
result, "Title", null);
LivLog.info(this.getClass(), "bit map conversion is" + result
+ path);
}
// 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;
}
}
How to resolve this?
Here is how you'd convert Bitmap to Uri:
private Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Pass Bitmap while calling this method:
getImageUri(this,bitmap);
try below code:-
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
for more info see below link:-
http://colinyeoh.wordpress.com/2012/05/18/android-getting-image-uri-from-bitmap/
I was wondering how i set a buttons background image from a URL on android.
The buttons id is blue if you need to know that.
I tried this but it didn't work.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.
public Bitmap generateBitmap(String url){
bitmap_picture = null;
int intentos = 0;
boolean exception = true;
while((exception) && (intentos < 3)){
try {
URL imageURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
conn.connect();
InputStream bitIs = conn.getInputStream();
if(bitIs != null){
bitmap_picture = BitmapFactory.decodeStream(bitIs);
exception = false;
}else{
Log.e("InputStream", "Viene null");
}
} catch (MalformedURLException e) {
e.printStackTrace();
exception = true;
} catch (IOException e) {
e.printStackTrace();
exception = true;
}
intentos++;
}
return bitmap_picture;
}
Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463
Try this code:
Bitmap bmpbtn = loadBitmap(yoururl);
button1.setImageBitmap(bmpbtn);
I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String